PUTting and DELETEing in python urllib2
Tuesday, October 21st, 2008The urllib2 Python module makes it pretty simple to GET and POST data using HTTP (and other protocols). But there isn’t a good built-in way to issue HTTP PUT or DELETE requests. I ran into this limitation while working on a project to upload automatically generated documentation to the Mozilla Developer Center. The DekiWiki API for uploading an file attachment uses the HTTP PUT method.
It turns out there is an easy workaround. You can subclass the urllib2.Request class and explicitly override the method:
import urllib2 class RequestWithMethod(urllib2.Request): def __init__(self, method, *args, **kwargs): self._method = method urllib2.Request.__init__(*args, **kwargs) def get_method(self): return self._method
Preview for Thursday’s post: the generated documentation is already online.