2024-03-29 11:56:05 发布
网友
urllib2是否支持DELETE或PUT方法?如果是,请举例说明。我需要使用活塞API。
urllib2
您可以对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
由Benjamin Smedberg提供
更正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()
你可以用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)
您可以对urllib2.Request对象进行子类化,并在实例化该类时重写该方法。
由Benjamin Smedberg提供
更正Raj的回答:
你可以用httplib来完成:
还有,看看这个question。接受的答案显示了向urllib2添加其他方法的方法:
相关问题 更多 >
编程相关推荐