Friday, February 12, 2010

python: make an HTTP request with any kind of HTTP method (put, delete, head) using urllib2

Sometimes you don't want to sit and migrate all your existing codebase from urllib/urllib2 to httplib/httplib2, just because the former doesn't support HTTP PUT or HTTP DELETE methods out-of-the-box. Well, here's a workaround for just that problem:
import urllib2
opener = urllib2.build_opener(urllib2.HTTPHandler)
request = urllib2.Request('http://example.org', data='your_put_data')
request.add_header('Content-Type', 'your/contenttype')
request.get_method = lambda: 'PUT'
url = opener.open(request)


Thanks to stackoverflow yet again for solving another programming conundrum :)

No comments: