views:

43

answers:

1

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

+1  A: 

You could subclass urllib2.Request like so (untested)

import urllib2

class MyRequest(urllib2.Request):
    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='PUT')

resp = opener.open(req)
sdolan
This is exactly what I was looking to do. Extend the urllib2 module to override the method. Ahh the beauty of python. One change while calling init on Request... urllib2.Request.__init__(self, ....)
sbartell
@sbartell: Glad it worked out... I've updated the __init__ to include the self and also change the get_method to return the super classes default rather than just copy it's method over.
sdolan