Book Image

Learning Python Network Programming

By : Dr. M. O. Faruque Sarker, Samuel B Washington, Sam Washington
Book Image

Learning Python Network Programming

By: Dr. M. O. Faruque Sarker, Samuel B Washington, Sam Washington

Overview of this book

Table of Contents (17 chapters)
Learning Python Network Programming
Credits
About the Authors
About the Reviewers
www.PacktPub.com
Preface
Index

Customizing requests


To make use of the functionality that headers provide, we add headers to a request before sending it. To do this, we can't just use urlopen(). We need to follow these steps:

  • Create a Request object

  • Add headers to the request object

  • Use urlopen() to send the request object

We're going to learn how to customize a request for retrieving a Swedish version of the Debian home page. We will use the Accept-Language header, which tells the server our preferred language for the resource it returns. Note that not all servers hold versions of resources in multiple languages, so not all servers will respond to Accept-LanguageLinux home page.

First, we create a Request object:

>>> from urllib.request import Request
>>> req = Request('http://www.debian.org')

Next we add the header:

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

The add_header() method takes the name of the header and the contents of the header as arguments. The Accept-Language header takes two-letter...