How to make HTTP DELETE method using urllib2?

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

+44
python urllib2
Dec 22 '10 at 17:02
source share
5 answers

you can do this with httplib :

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

also check question . the accepted answer shows a way to add other methods in 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) 
+69
Dec 22 '10 at 17:20
source

Correction for Raj's answer:

 import urllib2 class RequestWithMethod(urllib2.Request): def __init__(self, *args, **kwargs): self._method = kwargs.pop('method', None) urllib2.Request.__init__(self, *args, **kwargs) def get_method(self): return self._method if self._method else super(RequestWithMethod, self).get_method() 
+13
Jun 10 2018-11-22T00:
source

You can subclass the urllib2.Request object and override this method when instantiating the class.

 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 

Courtesy of Benjamin Smedberg

+7
Jan 18 2018-11-18T00:
source

You can define a subclass of the Request object and call it like this:

 import urllib2 class RequestWithMethod(urllib2.Request): def __init__(self, *args, **kwargs): self._method = kwargs.pop('method', None) urllib2.Request.__init__(self, *args, **kwargs) def get_method(self): return self._method if self._method else super(RequestWithMethod, self).get_method() def put_request(url, data): opener = urllib2.build_opener(urllib2.HTTPHandler) request = RequestWithMethod(url, method='PUT', data=data) return opener.open(request) def delete_request(url): opener = urllib2.build_opener(urllib2.HTTPHandler) request = RequestWithMethod(url, method='DELETE') return opener.open(request) 

(This is similar to the answers above, but shows usage.)

0
Jun 27 '17 at 13:18
source

Found the following code from https://gist.github.com/kehr/0c282b14bfa35155deff34d3d27f8307 and it worked for me (Python 2.7.5):

 import urllib2 request = urllib2.Request(uri, data=data) request.get_method = lambda: 'DELETE' response = urllib2.urlopen(request) 
0
Dec 07 '17 at 13:44 on
source



All Articles