urllib2
是否支持DELETE或PUT方法?如果是,请提供任何示例。我需要使用活塞API。
答案 0 :(得分:72)
您可以使用httplib:
执行此操作import httplib
conn = httplib.HTTPConnection('www.foo.com')
conn.request('PUT', '/myurl', body)
resp = conn.getresponse()
content = resp.read()
另外,请查看此question。接受的答案显示了一种向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)
答案 1 :(得分:13)
对Raj的回答进行更正:
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()
答案 2 :(得分:7)
您可以对urllib2.Request对象进行子类化,并在实例化该类时覆盖该方法。
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
答案 3 :(得分:2)
从https://gist.github.com/kehr/0c282b14bfa35155deff34d3d27f8307找到以下代码,它对我有用(Python 2.7.5):
import urllib2
request = urllib2.Request(uri, data=data)
request.get_method = lambda: 'DELETE'
response = urllib2.urlopen(request)
答案 4 :(得分:0)
您可以定义Request
对象的子类,并按如下方式调用它:
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)
(这与上述答案类似,但显示用法。)