Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

custom methods in python urllib2

Using urllib2, are we able to use a method other than 'GET' or 'POST' (when data is 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

like image 826
sbartell Avatar asked Sep 25 '26 02:09

sbartell


1 Answers

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)
like image 100
Sam Dolan Avatar answered Sep 26 '26 18:09

Sam Dolan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!