Saturday, 31 July 2004
The Whole Web in a Python Dictionary
A few days ago I blogged a straw-man API for client-side HTTP based on dictionaries. This turns out to be well-aligned with a project I’ve had on the back burner for a while; coming up with some Python APIs for HTTP that are usable, encourage good practice, and well-aligned with the specifications.
So, a first prototype is now available, with three modules defined; http.message, which defines common constructs for HTTP messages and their payloads, http.status, which enumerates the defined HTTP response status codes as exceptions to be raised during processing, and http.client, which currently contains a dictionary-like class along the lines discussed before.
For example, the following GETs the Apple home page, PUTs its representation to a fictional site, and then DELETEs it. When we try to access the new location, an exception corresponding to the HTTP error code is raised.
>>> from http.client import Dict >>> web = Dict() >>> apple = web['http://www.apple.com/'] >>> apple. __class__ <class http.message.Representation at 0x676c0> >>> web['http://www.example.org/apple.html'] = apple >>> del web['http://www.example.org/apple.html'] >>> new_apple = web['http://www.example.org/apple.html'] Traceback (most recent call last): File "", line 1, in ? File "http/client.py", line 50, in __getitem__ response = dereference(request) File "http/client.py", line 97, in dereference raise response http.status.NotFound >>>
The one difference to my previous straw-man is in POST, which now goes like this:
>>> from http import message >>> thing = message.Representation() >>> thing.body = "hello. this is the POST body." >>> thing.headers['content-type'] = "text/plain" >>> thing_creation_result = web('http://www.example.org/thingCreator', thing)
This library is barely usable and I have a lot of plans for it, as can be seen in its TODO list. First and foremost is to support HTTP authentication, so that the PUT and DELETE functionality are more practically usable.
Comments and suggestions appreciated.