Learning Python Network Programming

(Sean Pound) #1
Chapter 2

We can check if the response is in Swedish by printing out the first few lines:





response.readlines()[:5]





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


b'\n',


b'\n',


b' \n',


b' Debian -- Det universella operativsystemet \n']


Jetta bra! The Accept-Language header has informed the server about our preferred
language for the response's content.


To view the headers present in a request, do the following:





req = Request('http://www.debian.org')








req.add_header('Accept-Language', 'sv')








req.header_items()





[('Accept-language', 'sv')]


The urlopen() method adds some of its own headers when we run it on a request:





response = urlopen(req)








req.header_items()





[('Accept-language', 'sv'), ('User-agent': 'Python-urllib/3.4'),
('Host': 'www.debian.org')]


A shortcut for adding headers is to add them at the same time that we create the
request object, as shown here:





headers = {'Accept-Language': 'sv'}








req = Request('http://www.debian.org', headers=headers)








req.header_items()





[('Accept-language', 'sv')]


We supply the headers as a dict to the Request object constructor as the headers
keyword argument. In this way, we can add multiple headers in one go, by adding
more entries to the dict.


Let's take a look at some more things that we can do with headers.

Free download pdf