0

I may be poor at googling, but so far I have come up dry. Is there no such thing as a universal decoder for HTTP responses, where you give it the body and the headers, and it returns the decoded data?

For example:

response = requests.get("...")
body = clever_package.decode(response.body, response.headers)

This is using the requests package to get the data, though this isn't strictly necessary. Is there no universal decoder which takes the contentType and isBase64Encoded headers and works its magic?

Perhaps I'm not seeing an obvious flaw in such a package, which explains why I can't find it anywhere.

Cheers!

theooos
  • 1
  • 3

1 Answers1

0

What do you mean with decoding? Just bytes to string data? In that case, python-chardet would be what you are looking for for cases where the header doesn't specify the encoding (if the headers specify the decoding, just decode it from the encoding specified in the header).

If you want to parse XML, JSON, ... in different ways, you'd probably use the respective libraries (built-in json module, yaml module, etc..) after having decoded the data into a unicode string.

Thomas Perl
  • 2,178
  • 23
  • 20
  • I mean loading it into a meaningful data-type, such as a dictionary in Python in the example of json being the type. I have the following loc: ```if event['headers']['Content-Type'] == 'application/x-www-form-urlencoded': body = json.loads(urllib.parse.parse_qs(body)['payload'][0]) elif 'application/json' in event['headers']['Content-Type']: body = json.loads(body)``` and it seems silly to me that I wouldn't be able to reuse a function to get a dictionary from two different places without writing this clunky if-statement. I don't know, maybe I'm being silly. – theooos Aug 25 '17 at 08:22
  • If you are already using `requests`, the `response` object should have a `.json()` method that will raise an exception if it can't do JSON parsing. The other example with `application/x-www-form-urlencoded` looks very application-specific (it has JSON encoded in a `payload` form element, this is not generic). At best you could do try JSON, if that fails, check for `application/x-www-form-urlencoded` and do `parse_qs()` on it (and return that). – Thomas Perl Aug 25 '17 at 12:06
  • I don't know how I missed the .json method... I will use that. Having given it some though I can see that the idea of a method that parses all types is quite useless. You're right though about the payload format, it's PaperTrail's very weird API. – theooos Aug 27 '17 at 00:15