pythonurllib2中的自定义方法

2024-04-24 01:25:29 发布

您现在位置:Python中文网/ 问答频道 /正文

使用urllib2,我们是否可以使用“GET”或“POST”以外的方法(当提供数据时)?在

我深入研究了这个库,似乎使用GET或POST的决定与请求中是否提供了数据“方便”相关。在

例如,我想与CouchDB数据库交互,该数据库需要诸如“DEL”、“PUT”之类的方法。我需要urllib2的处理程序,但需要自己进行方法调用。在

我不希望将第三方模块导入到我的项目中,比如CouchDB python api。所以请不要走那条路。我的实现必须使用Python2.6附带的模块。(我的设计规范要求使用barebones可移植python发行版)。在导入外部模块之前,我会使用httplib编写自己的接口。在

非常感谢你的帮助


Tags: 模块数据项目方法api数据库处理程序get
2条回答

可能是:

import urllib2

method = 'PATH'
request = urllib2.Request('http://host.com')
request.get_method = lambda: method()

也就是说,一个运行时类修改,也称为monkey path。在

您可以像这样子类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)

相关问题 更多 >