Python urllib2中的自定义方法

3 投票
2 回答
1986 浏览
提问于 2025-04-16 05:09

使用urllib2时,我们能否使用除了'GET'或'POST'以外的方法(当提供数据时)?

我查了一下这个库,发现选择使用GET还是POST的方法,似乎是和请求中是否提供数据“方便地”挂钩的。

举个例子,我想和一个CouchDB数据库进行交互,这个数据库需要使用像'DEL'和'PUT'这样的请求方法。我想用urllib2的处理功能,但需要自己调用这些方法。

我更希望不在我的项目中导入第三方模块,比如CouchDB的Python API。所以我们就不讨论这个了。我的实现必须使用Python 2.6自带的模块。(我的设计要求使用一个简单的PortablePython版本)。在导入外部模块之前,我会使用httplib自己写一个接口。

非常感谢你的帮助

2 个回答

0

这可能是:

import urllib2

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

也就是说,这是一种运行时类的修改,通常叫做“猴子补丁”。

7

你可以像这样创建一个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)

撰写回答