开发者

custom methods in python urllib2

Using urllib2, are we able to use a method other than 'GET' or 'POST' (when data i开发者_开发技巧s provided)?

I dug into the library and it seems that the decision to use GET or POST is 'conveniently' tied to whether or not data is provided in the request.

For example, I want to interact with a CouchDB database which requires methods such as 'DEL', 'PUT'. I want the handlers of urllib2, but need to make my own method calls.

I WOULD PREFER NOT to import 3rd party modules into my project, such as the CouchDB python api. So lets please not go down that road. My implementation must use the modules that ship with python 2.6. (My design spec requires the use of a barebones PortablePython distribution). I would write my own interface using httplib before importing external modules.

Thanks so much for the help


You could subclass urllib2.Request like so (untested)

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)


It could be:

import urllib2

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

That is, a runtime class modification A.K.A monkey path.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜