From: Michael Tremer Date: Wed, 30 Nov 2016 10:43:23 +0000 (+0100) Subject: http: Allow decoding of received content X-Git-Tag: 0.9.28~1285^2~1458 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=30ec36743678ef4a36e7611ad29fb20dc51d6cee;p=pakfire.git http: Allow decoding of received content 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 --- diff --git a/src/pakfire/http.py b/src/pakfire/http.py index adaeb98ad..2fc1195c1 100644 --- a/src/pakfire/http.py +++ b/src/pakfire/http.py @@ -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