XML technologies / XML / Python & XML / The Python Internet APIs / Working with URLs
(Excerpt from “Python & XML” by Christopher A. Jones & Fred L. Drake, Jr.)
A URL packs a great deal of Internet information into one string. It names the server, the file on that server, any data you supply to generate a dynamic response, and even the protocol for retrieving the information. A simple URL looks like this:
"http://www.oreilly.com/oreilly/about.html"
This URL has three parts. The first tells you or your software which protocol to use for the resource. Here it is HTTP, indicated by http:. The next part specifies the server name and domain. Here the server is www and the domain is oreilly.com, together forming //www.oreilly.com. Next come a pathname (/oreilly/ ) and a filename (about.html). From this information, your browser brilliantly deduces that it should connect over HTTP to www on oreilly.com and retrieve the file /oreilly/about.html.
URLs can of course be more complicated. If you type “Python” into a search form and submit it, your browser might visit a URL like this:
"http://search.oreilly.com/cgi-bin/search?term=Python&category=All&pref=all"
Now there are more parts to examine. First, the server changed from www to search. Second, the path is now /cgi-bin/ rather than /oreilly/. The filename about.html was replaced by a new target called search. Most interesting, however, are the question mark and following data:
?term=Python&category=All&pref=all This part is known as the query string. If search is a CGI program or something similar within an application server, the query string is passed to it as an environment variable. The CGI program can dissect it to determine that a variable named term is set to Python, and that category and pref equal All and all respectively. As you can imagine, this information matters to the O’Reilly database, which returns the appropriate product information to your browser.
Suppose instead that you searched the O’Reilly site for “Python!” rather than “Python.” What would the URL look like? The only difference is that the exclamation mark is URL-encoded. Only a few special characters are allowed in a URL; others are represented by their hexadecimal code, delimited by a percent sign (%). This time the query string looks slightly different:
?term=Python%21&category=All&pref=all The exclamation mark is now replaced by %21, its URL-encoded equivalent.
Encoding URLs
When generating a URL programmatically to pass data to a website, supply query-string parameters as shown above.
You may need to construct URLs programmatically when integrating Python with a dynamic website expecting query-string parameters.
The Python module urllib contains the function urlencode. It takes a dictionary of key/value pairs and returns a correctly formatted query string to include in a URL. For a dictionary of any size, call urlencode with the dictionary as its parameter, as shown here:
>>> from urllib import urlencode
>>> myDict = {
... "Name" : "Chris Jones",
... "Adresse" : "Woodinville, WA",
... "Lieblingszeichen" : "#, @, $ und %"
... }
>>> strUrl = urlencode(myDict)
>>> print strUrl
Adresse=Woodinville%2c+WA&Name=Chris+Jones&Lieblingszeichen=%23%2C+%40%2C+%24+und+%25Here, strURL is not a complete URL; it contains only the query data at the end. The first half must contain the protocol, server and domain:
http://www.example.com/search.cgi?Adresse=Woodinville%2c+WA&Name=Chris+Jones&Lieblingszeichen=%23%2C+%40%2C+%24+und+%25The function urlencode automatically translates special characters such as #, @, $ und % to %23%2C+%40%2C+%24+und+%25. Not only special characters but also commas and spaces have been converted to hexadecimal values.
Encoding URLs
The function quote from urllib performs for a single data string the encoding that urlencode performs with a dictionary parameter. The main difference is that quote does not automatically generate key/value pairs from a dictionary. The function quote exists to convert a single string to URL-safe syntax. If your URL is "http://www.example.com/addQuotation.cgi?myquote=" and you need to add a value while retaining a valid URL, use the function quote to encode it:
>>> from urllib import quote
>>> quote('Zitat: "Ich denke, also bin ich."')
'Zitat%3A%20%22Ich%20denke%2C%20also%20bin%20ich.%22'Most importantly, remember that quote should encode a single string, not a key/value pair. In every key=value pair, only the value should be encoded with the quote function. If you included the myquote= part or key of the query string when calling quote, the equals sign would also be encoded, rendering the URL useless.
Decoding URLs
What works in one direction must also work in reverse. If you encode URLs in your programs, sooner or later you will probably need to decode one. The function unquote from urllib takes an encoded string, for example one created with quote, and returns its decoded version:
>>> from urllib import unquote
>>> unquote('Zitat%3A%20%22Ich%20denke%2C%20also%20bin%20ich.%22')
'Zitat: "Ich denke, also bin ich."'If you construct and dissect URLs programmatically, it follows that making a connection with one should also make sense.
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