Does urllib2
support DELETE or PUT method? If yes provide with any example please. I need to use piston API.
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.
urllib2 is deprecated in python 3. x. use urllib instaed.
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.
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.
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)
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With