Learning Python Network Programming

(Sean Pound) #1

HTTP and Working with the Web


And we can look at properties of the response object. Try:





response.status_code
200
response.reason
'OK'
response.url
'http://www.debian.org/'
response.headers['content-type']
'text/html'





Note that the header name in the preceding command is in lowercase. The keys in
the headers attribute of Requests response objects are case insensitive.


There are some convenience attributes that have been added to the response object:





response.ok
True





The ok attribute indicates whether the request was successful. That is, the request
contained a status code in the 200 range. Also:





response.is_redirect
False





The is_redirect attribute indicates whether the request was redirected. We can
also access the request properties through the response object:





response.request.headers
{'User-Agent': 'python-requests/2.3.0 CPython/3.4.1 Linux/3.2.0-4-
amd64', 'Accept-Encoding': 'gzip, deflate', 'Accept': '/'}





Notice that Requests is automatically handling compression for us. It's including
gzip and deflate in an Accept-Encoding header. If we look at the Content-
Encoding response, then we will see that the response was in fact gzip compressed,
and Requests transparently decompressed it for us:





response.headers['content-encoding']
'gzip'





We can look at the response content in many more ways. To get the same bytes
object as we got from an HTTPResponse object, perform the following:





response.content
b'<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">\n...




Free download pdf