20 12 / 2010
Making a HTTP DELETE request with urllib2
Yet another post to overcome yet another urllib2 quirk. Using the default urllib2 module shipped with python, one can only make HTTP GET and POST requests. The code that decides which method to use is something like this (in urllib2.Request)
def get_method(self):
if self.has_data():
return 'POST'
else:
return 'GET'
Thankfully you can make DELETE (and also HEAD and PUT requests as I’m told) by sub classing from urllib2.Request and overriding get_method method.
class RequestWithMethod(urllib2.Request):
"""Workaround for using DELETE with urllib2"""
def __init__(self, url, method, data=None, headers={},\
origin_req_host=None, unverifiable=False):
self._method = method
urllib2.Request.__init__(self, url, data, headers,\
origin_req_host, unverifiable)
def get_method(self):
if self._method:
return self._method
else:
return urllib2.Request.get_method(self)
The usage of our shiny new inherited class to make a DELETE request goes as follows
req = RequestWithMethod(url, 'DELETE')
urllib2.urlopen(req)
Hope this post saves you hours of googling and experimenting.
Update: Thanks to commenter Gherron for pointing out a bug and improving the code.