使用urllib2,我们是否能够使用'GET‘或'POST’以外的方法(当提供数据时)?
我深入研究了这个库,似乎使用GET或POST的决定与请求中是否提供数据“方便”相关。
例如,我想要与一个CouchDB数据库交互,该数据库需要'DEL‘、'PUT’等方法。我需要urllib2的处理程序,但需要进行我自己的方法调用。
我不希望将第三方模块导入到我的项目中,比如CouchDB python api。所以,请不要走这条路。我的实现必须使用Python2.6附带的模块。(我的设计规范要求使用基本的PortablePython发行版)。在导入外部模块之前,我会使用httplib编写自己的接口。
非常感谢你的帮助
发布于 2010-10-08 02:40:14
您可以子类urllib2.Request,如下所示(未测试)
import urllib2
class MyRequest(urllib2.Request):
GET = 'get'
POST = 'post'
PUT = 'put'
DELETE = 'delete'
def __init__(self, url, data=None, headers={},
origin_req_host=None, unverifiable=False, method=None):
urllib2.Request.__init__(self, url, data, headers, origin_req_host, unverifiable)
self.method = method
def get_method(self):
if self.method:
return self.method
return urllib2.Request.get_method(self)
opener = urllib2.build_opener(urllib2.HTTPHandler)
req = MyRequest('http://yourwebsite.com/put/resource/', method=MyRequest.PUT)
resp = opener.open(req)
发布于 2018-08-02 05:01:13
可能是:
import urllib2
method = 'PATH'
request = urllib2.Request('http://host.com')
request.get_method = lambda: method()
也就是说,运行时类修改又称猴子路径。
https://stackoverflow.com/questions/3884695
复制相似问题