How to make HTTP DELETE method using urllib2?

Pol picture Pol · Dec 22, 2010 · Viewed 39.4k times · Source

Does urllib2 support DELETE or PUT method? If yes provide with any example please. I need to use piston API.

Answer

Corey Goldberg picture Corey Goldberg · Dec 22, 2010

you can do it with httplib:

import httplib 
conn = httplib.HTTPConnection('www.foo.com')
conn.request('PUT', '/myurl', body) 
resp = conn.getresponse()
content = resp.read()

also, check out this question. the accepted answer shows a way to add other methods to urllib2:

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)