XML technologies / XML / Python & XML / Python’s Internet APIs / Connecting over HTTP
(Excerpt from “Python & XML” by Christopher A. Jones & Fred L. Drake, Jr.)
Although urllib may suit Internet files, more elaborate HTTP communication may be needed. A Python program connecting two websites may need cookie headers or emulate a browser by putting its name in User-Agent when a site demands the latest Internet Explorer. In these cases, httplib rather than urllib gives finer control.
Communicating over HTTP
Browser-server HTTP conversations contain headers and data, revealing much about both parties. Headers preceding server content and browser requests carry client and server metadata. Entering a URL sends a complete request such as:
GET /c7/favquote.cgi HTTP/1.1
Host: www.python.org
Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg
Accept-Language: en-us
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/4.0 (compatible; MSIE 5.5; Windows 98; Win 9x 4.90)
Connection: Keep-AliveHeaders describe browser capabilities. The first line (GET /c7/favquote.cgi HTTP/1.1) identifies a GET request for /c7/favquote.cgi using HTTP 1.1. Other data specifies accepted file types, browser identity and connection type. The Accept lines advertise support for .gif and .jpeg and others. Three header lines start with Accept: the browser accepts en-us as language and both gzip and deflate as encodings.
Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg
Accept-Language: en-us
Accept-Encoding: gzip, deflateThe User-Agent tells the server which browser or HTTP client you use. All browsers and HTTP libraries populate it. Some websites specifically target Netscape Navigator or Internet Explorer, redirecting to different pages based on the User-Agent string:
User-Agent: Mozilla/4.0 (compatible; MSIE 5.5; Windows 98; Win 9x 4.90) Here the agent is Internet Explorer 5.5 on Windows. The last header entry specifies connection type, here Keep-Alive:
Connection: Keep-Alive The Keep-Alive connection type keeps the client-server socket open for further resources. Loading a page first retrieves HTML, then images referenced by img tags, stylesheets and framesets. Reconnecting for each is slow, especially on graphics-heavy pages. With Keep-Alive, the browser reuses the channel for remaining downloads.
Request types
Besides GET, there are three request types. A browser can retrieve a file with GET or send data, such as a CGI form, with POST. The lesser-known types are HEAD and PUT. The former, HEAD, fetches only headers; PUT uploads a file.
GETRequests a file, optionally with a query string used by CGI or another executable resource to generate dynamic data.
POSTSends a large URL-encoded data packet, often form fields. Anything sent using
POSTcan also be sent usingGET, but the query string forGETcan become long and unwieldy. APOSTis not in the query string and is invisible to users. Servers may limit query-string size yet accept largerPOSTrequests.HEADLike
GET, but returns headers only.PUTA rarely used upload method. The filename normally following
GETorPOSTbecomes the name of the uploaded content. Instead of asking withGETfor a page named /index.html, ask withPUTto store a file named /index.html. DuringPUT, file content follows headers as inPOST.
Retrieving a document with Python
For manual HTTP in Python, use httplib. The httplib standard module belongs to Python 2.x. Its class HTTP in httplib offers these connection methods:
Req = HTTP(address, [port])
Returns an HTTP instance used as request object, connecting to the given address and optional port. Most servers use port 80, so this argument is optional. For other ports, select a specific port.
Req.putrequest(method, file)
Sends the initial request with filename and HTTP version, the first header line, as in:
GET /c7/favquote.cgi HTTP/1.1 Req.putheader(header-type, value)
Adds a header, including custom User-Agent, Accept-Types strings or cookies.
Req.endheaders( )
Ends the headers. HTTP separates headers and data with a blank line: server headers, blank line, then HTML. When a browser submits a form with POST, it uses the same separation.
Req.send(data)
Sends data after the request. Call send after endheaders for protocol compliance. Use with POST or PUT.
ErrorCode, ErrorMessage, Headers = Req.getreply( )
Returns server headers and response code together. ErrorCode and ErrorMessage should be 200 and OK on success. The Headers object is actually an instance of mimetools.Message.
fp. = Req.getfile( )
Returns a file-like object for the actual HTML or other document.
Using the HTTP class from httplib is easy. This example connects to a server and retrieves index.html.
Example: Making an HTTP request
>>> from httplib import HTTP
>>> req = HTTP("www.example.com")
>>> req.putrequest("GET", "/index.html")
>>> req.putheader("Accept", "text/html")
>>> req.putheader("User-Agent", "MeinPythonSkript")
>>> req.endheaders( )
>>> ec, em, h = req.getreply( )
>>> print ec, em
200 OK
>>> fd = req.getfile( )
>>> textlines = fd.read( )
>>> fd.close( )The steps are simple: call the HTTP class with the server, "www.example.com", then add headers specifying accepted data and the agent name, here MeinPythonSkript. Calling getreply retrieves the error code and message, printed on the console:
>>> print ec, em
200 OK Next use getfile to obtain the file-like object containing the document. The method getfile returns a readable descriptor. Calling read assigns the result to textlines, now containing the document. Calling close ends the request. Print textlines to see the result:
>>> print textlines
<html>
<head>
<link rel="stylesheet" type="text/css" href="/zpath.css">
</head>
<body BGCOLOR="#CDFF00">
<p>
<table WIDTH=100% height=100%>
<tr>
<td VALIGN="top" ALIGN="left"><a HREF="/cgi-bin/start.cgi?page=top"><img SRC="images/zplogo.gif" WIDTH=457 HEIGHT=144 BORDER=0></a></td>
</tr>
</table>
</p>
</body>
</html>Pay attention to the User-Agent string. Most administrators collect browser usage statistics. Your Python Internet programs can contribute. In the example Making an HTTP request, we set User-Agent to MeinPythonSkript:
req.putheader("User-Agent", "MeinPythonSkript") This enters server logs, probably appearing in the under-one-percent category of the administrator’s browser statistics.
Building query strings with httplib
The example Making an HTTP request retrieves one file. To add a query string to GET, the second argument to HTTP.putrequest is the filename. Append your data, presumably URL-encoded:
req.putrequest("GET", "/handler.cgi?id=12345") For special characters, use urllib.quote, discussed under Encoding URLs.
req.putrequest("GET", "/handler.cgi?" + quote("numbers=1/2/3/4/5")) Baking cookies for the server
Hungry administrators will be disappointed that browser cookies are purely electronic. They identify a browser: it keeps the cookie and resends it to the same site or document. The server can personalize content or link you to database data such as a profile or shopping cart. Python scripts may also need cookies in headers. Use the HTTP class’s putheader method:
req.putheader("Cookie", "key=value") Conversely, server cookies arrive in a set-cookie header alongside others for the browser to process.
Performing a POST operation
Manual HTTP often moves documents between sites. You might query a database, build a form and send its data elsewhere with POST. A POST using httplib is relatively simple, but more involved than earlier examples. The next sections explain it.
Creating a POST receiver
A POST example needs a destination. Create a simple CGI script echoing submitted data. Copy this ten-line file as favquote.cgi into a CGI-capable server directory:
Example: favquote.cgi
#!/usr/bin/python
import cgi
form = cgi.FieldStorage( )
favquote = form["favquote"].value
print "Content-type: text/html"
print ""
print "<html><body>"
print "Ihr Zitat lautet: "
print favquote
print "</body></html>"This uses the module cgi to receive POST data. Next we send a POST to it.
Ensuring correct URL encoding
An important part of POST is correctly encoding data. Do not encode the key favquote if CGI expects a variable named favquote. A correct key/value pair is:
favquote=Mein%20Zitat%20lautet%3A%20%22Ich%20denke%2C%20also%20bin%20ich.%22 Encoding the entire string rather than only the value produces:
favquote%3dMein%20Zitat%20lautet%3A%20%22Ich%20denke... The server then has no usable key because favquote= became favquote%3d.
Performing POST with httplib
In the example Making an HTTP request, we built a GET request using httplib. A POST requires special calls in precise order. HTTP call order matters, and POST needs extra headers. Starting a POST resembles GET:
req = HTTP("127.0.0.1")
req.putrequest("POST", "/c7/favquote.cgi")
req.putheader("Accept", "text/html")
req.putheader("User-Agent", "MeinPythonSkript")The first argument of putrequest is now POST. Apart from changing GET to POST, the call to putrequest looks the same. The server must know the exact byte count. Headers use line ends and a blank line as delimiters, but data may contain binary or nonprinting characters. Instead, specify a byte count for the server to read, using putheader, knowing how many bytes you will send:
myquote = 'Mein Lieblingszitat lautet: "Ich denke, also bin ich."'
postdata = "favquote=" + quote(myquote)
req.putheader("Content-Length", str(len(postdata)))Build the Post data by joining the key (favquote=) and encoded value. Use len to measure the encoded string postdata. Since putheader requires a string second argument, not a number, convert the length with str.
Use the method HTTP.send to send data after ending headers:
req.endheaders( )
req.send(postdata)Now retrieve and read the response as in the earlier GET request in favquote.cgi. The result from POST may be dynamic data such as search results, or HTML reporting a problem with the POST request.
A complete POST operation
As shown, POST takes extra steps compared with GET. The file post.py combines these ideas in a complete POST operation. Copy favquote.cgi into a CGI directory, then run post.py from the command line. Use the appropriate IP address or localhost when calling the HTTP constructor.
Example: post.py
"""
post.py
"""
from httplib import HTTP
from urllib import quote
# Erstelle POST-Daten
myquote = 'Mein Lieblingszitat lautet: "Ich denke, also bin ich."'
# Sicherstellen, daß key= ausgenommen bleibt...
postdata = "favquote=" + quote(myquote)
print "Werde ", len(postdata), "Bytes POSTen:"
print postdata
# Beginne HTTP-Anfrage
req = HTTP("127.0.0.1") # nehmen Sie eine andere IP, falls nötig
req.putrequest("POST", "/c7/favquote.cgi")
req.putheader("Accept", "text/html")
req.putheader("User-Agent", "MeinPythonSkript")
# Setze Content-length auf Länge von postdata
req.putheader("Content-Length", str(len(postdata)))
req.endheaders( )
# Sende postdata nach Beenden des Headers,
# CGI-Skript wird es auf STDIN empfangen
req.send(postdata)
ec, em, h = req.getreply( )
print "HTTP RESPONSE: ", ec, em
# Hole dateiähnliches Objekt aus HTTP-Antwort
# und gib empfangenes HTML auf Bildschirm aus
fd = req.getfile( )
textlines = fd.read( )
fd.close( )
print "\nFolgendes HTML erhalten:\n"
print textlines Here are the raw headers and Post data produced by post.py:
POST /c7/favquote.cgi HTTP/1.1
Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg
Accept-Language: en-us
Content-Type: application/x-www-form-urlencoded
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/4.0 (compatible; MSIE 5.5; Windows 98; Win 9x 4.90)
Host: 192.168.1.45
Content-Length: 70
Connection: Keep-Alive
favquote=Mein+Lieblingszitat+lautet%3A+%22Ich+denke%2C+also+bin+ich.%22The content length is specified, with data immediately after the blank line following headers.
We have used urllib and httplib to retrieve generic URLs and make specific HTTP requests. Next examine Python’s server-side connection support.
Copyright © 2002 O'Reilly Verlag GmbH & Co. KG
You may print the online version for your private use.
Otherwise, this chapter from “Python & XML” is subject to the same conditions as the bound edition: the work, including all its parts, is protected by copyright. All rights reserved, including reproduction, translation, microfilming, and storage and processing in electronic systems.
O’Reilly Verlag GmbH & Co. KG, Balthasarstraße 81, 50670 Köln, kommentar(at)oreilly.de