]> git.ipfire.org Git - pakfire.git/commitdiff
http: Allow decoding of received content
authorMichael Tremer <michael.tremer@ipfire.org>
Wed, 30 Nov 2016 10:43:23 +0000 (11:43 +0100)
committerMichael Tremer <michael.tremer@ipfire.org>
Wed, 30 Nov 2016 10:43:23 +0000 (11:43 +0100)
This allows to let the module decode JSON content right
away so that this doesn't have to be handled in the module
that is using the HTTP client.

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

index adaeb98ad4e92ddc6e44142bffce24e1f11a41cf..2fc1195c1ec4270a072a389e4ed046c4588c28a4 100644 (file)
@@ -20,6 +20,7 @@
 ###############################################################################
 
 import base64
+import json
 import logging
 import ssl
 import urllib.parse
@@ -117,12 +118,34 @@ class Client(object):
 
                return res
 
-       def _one_request(self, url, **kwargs):
+       def _one_request(self, url, decode=None, **kwargs):
                r = self._make_request(url, **kwargs)
 
                # Send request and return the entire response at once
                with self._send_request(r) as f:
-                       return f.read()
+                       content = f.read()
+
+                       # Decode content
+                       if decode:
+                               content = self._decode_content(decode, content)
+
+                       return content
+
+       def _decode_content(self, type, content):
+               assert type in ("json")
+
+               # Decode from bytes to string
+               content = content.decode("ascii")
+
+               # Parse JSON
+               try:
+                       if type == "json":
+                               content = json.loads(content)
+
+               except ValueError as e:
+                       raise DecodeError() from e
+
+               return content
 
        def get(self, url, **kwargs):
                """
@@ -316,3 +339,11 @@ class MaxTriedExceededError(errors.Error):
                Raised when the maximum number of tries has been exceeded
        """
        pass
+
+
+class DecodeError(errors.Error):
+       """
+               Raised when received content could not be decoded
+               (e.g. JSON)
+       """
+       pass