Custom methods in python urllib2

Using urllib2, can we 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 "convenient" due to whether the data is provided in the request.

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

I PREVENT NOT TO import third-party modules into my project, e.g. python couchDB. So, please, do not go down this road. My implementation should use the modules that come with python 2.6. (My design specification requires the use of the PortablePython barebone distribution). I would write my own interface using httplib before importing external modules.

Thank you very much for your help

+3
source share
1 answer

You can 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)
+7
source

Source: https://habr.com/ru/post/1768482/


All Articles