Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make HTTP DELETE method using urllib2?

Tags:

python

urllib2

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

like image 684
Pol Avatar asked Dec 22 '10 17:12

Pol


People also ask

How do I use urllib2?

Simple urllib2 scripturlopen('http://python.org/') print "Response:", response # Get the URL. This gets the real URL. print "The URL is: ", response. geturl() # Getting the code print "This gets the code: ", response.

Is urllib2 deprecated?

urllib2 is deprecated in python 3. x. use urllib instaed.

What is the difference between Urllib and urllib2?

1) urllib2 can accept a Request object to set the headers for a URL request, urllib accepts only a URL. 2) urllib provides the urlencode method which is used for the generation of GET query strings, urllib2 doesn't have such a function. This is one of the reasons why urllib is often used along with urllib2.

What would you use Urllib request for?

The urllib. request module defines functions and classes which help in opening URLs (mostly HTTP) in a complex world — basic and digest authentication, redirections, cookies and more. The Requests package is recommended for a higher-level HTTP client interface.


2 Answers

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) 
like image 195
Corey Goldberg Avatar answered Sep 28 '22 08:09

Corey Goldberg


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() 
like image 42
Dave Avatar answered Sep 28 '22 09:09

Dave