demianbrecht / sanction

A dead simple OAuth2 client implementation.
MIT License
189 stars 43 forks source link

Add support for raw responses #13

Open poke opened 10 years ago

poke commented 10 years ago

Sometimes it can be very useful to be able to access the raw response object, instead of it being automatically read and passes through the specified parser. That way, one can access the response headers and read additional information from there.

For example, GitHub’s API will put rate limit information into X-Rate-Limit-* headers. With the current means, there is no possibility to access this information—other than requesting the rate limit status itself separately.

Another useful example is the StackExchange gzip compression which is part of your example. Usually, you shouldn’t blindly decompress responses just because you know that the server returns compressed results. Instead, servers are required to send the Content-Encoding HTTP header, specifying the used compression. Unless that header is set, you shouldn’t decompress it.

This pull requests adds an optional raw parameter to the Client.request method. Setting this to True will make the client return the raw response object instead of reading it and parsing it with the parser.

For the StackExchange example, it could be used like this then:

response = client.request('/query', raw=True)
content = response.read()
if response.headers.get('content-encoding') == 'gzip':
    content = gzip.decompress(content)
data = json.loads(content.decode())

Going further, it might make sense to actually pass the request object to the parser directly, passing all available information to it. But I didn’t want to introduce too many changes now, and especially didn’t want to break the compatibility.