]> git.ipfire.org Git - pakfire.git/commitdiff
http: Convert data argument according to method
authorMichael Tremer <michael.tremer@ipfire.org>
Wed, 30 Nov 2016 17:09:48 +0000 (18:09 +0100)
committerMichael Tremer <michael.tremer@ipfire.org>
Wed, 30 Nov 2016 17:09:48 +0000 (18:09 +0100)
data is a dict() with various arguments that are either
posted in the body of the request (POST) or added to the
URL (GET).

For a simple way to send requests, the HTTP client takes
care of building a correct request.

Signed-off-by: Michael Tremer <michael.tremer@ipfire.org>
src/pakfire/http.py

index 81e88d495df625895e1694ea819fc1bad297e70b..c8460197acdf24ccd7e9d46a58e9caa5a7c5f31f 100644 (file)
@@ -67,7 +67,21 @@ class Client(object):
                if self.baseurl:
                        url = urllib.parse.urljoin(self.baseurl, url)
 
-               req = urllib.request.Request(url)
+               # Encode data
+               if data:
+                       data = urllib.parse.urlencode(data)
+
+                       # Add data arguments to the URL when using GET
+                       if method == "GET":
+                               url += "?%s" % data
+                               data = None
+
+                       # Convert data into Bytes for POST
+                       elif method == "POST":
+                               data = bytes(data, "ascii")
+
+               # Create a request
+               req = urllib.request.Request(url, data=data)
 
                # Add our user agent
                req.add_header("User-Agent", "pakfire/%s" % PAKFIRE_VERSION)
@@ -81,6 +95,11 @@ class Client(object):
                for protocol, host in self.proxies.items():
                        req.set_proxy(host, protocol)
 
+               # When we send data in a post request, we must set the
+               # Content-Length header
+               if data and method == "POST":
+                       req.add_header("Content-Length", len(data))
+
                # Check if method is correct
                assert method == req.get_method()