PUTting and DELETEing in python urllib2
The 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.
October 23rd, 2008 at 2:25 am
Cool stuff. FYI, you can use graphviz in MindTouch Deki to create graphs and diagrams. Documentation here: http://wiki.developer.mindtouch.com/MindTouch_Deki/Extensions/Graphviz
November 2nd, 2008 at 7:05 pm
Great hack…think you’re missing the self in call to urllib2.Request.__init__(*args, **kwargs) so it should read urllib2.Request.__init__(self, *args, **kwargs)
~jason
October 17th, 2010 at 4:13 pm
The recipe you give does not work, at least not under my Python 2.6.5. However, this does and is backward-compatible:
class RequestWithMethod(urllib2.Request):
“Hack for forcing the method in a request – allows PUT and DELETE”
def __init__(self, method, *args, **kwargs):
# This assignment works directly in older Python versions
self._method = method
urllib2.Request.__init__(self, *args, **kwargs)
def get_method(self):
“Deduce the HTTP method to use.”
# This method works in newer Pythons (2.6.5, possibly earlier).
if self._method:
return self._method
elif self.has_data():
return “POST”
else:
return “GET”
It is possible that get_method() was recently introduced to solve this exact problem; in fact, I’d bet on it.
October 17th, 2010 at 4:15 pm
I indented that code. The blog engine smashed it left. The key point is that newer Pythons have a get_method() you can override.