-2

Why can I not change method to PUT. Can I change to PUT without too many code changes?

Here is my code:

cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
urllib2.install_opener(opener)   

#code to change method to PUT
opener.get_method = lambda: 'PUT'

print "now using method:", meth  # prints now using PUT

try:
    r = opener.open("http://the_url")
except urllib2.HTTPError as e:
    if hasattr(e, 'code'):
        report += "HTTP error status " + str(e.code) + " FAIL\n"
        if hasattr(e, 'reason'):
            print "HTTP Error reason " + e.reason
    else:
        report += "HTTP error occurred FAIL\n"

But I get runtime error HTTP Error reason Request method 'POST' not supported PUT session test HTTP error status 405 FAIL

Ankur Ankan
  • 2,953
  • 2
  • 23
  • 38
Angus Comber
  • 9,316
  • 14
  • 59
  • 107
  • Please, your life will be easier: http://docs.python-requests.org/en/latest/ – Marcin Jul 24 '13 at 16:58
  • 1
    Please provide a [short, self-contained correct example](http://sscce.org) demonstrating your problem. The code you've included isn't one: it crashes if you try to run it, and uses variables (e.g. `meth`) not defined anywhere. – Ilmari Karonen Jul 24 '13 at 17:11
  • This is a duplicate of https://stackoverflow.com/questions/111945/is-there-any-way-to-do-http-put-in-python – jdhildeb Apr 09 '20 at 19:41

1 Answers1

0

It seems urllib2 only supports GET and POST. I decided to use Apache Requests lib instead.

The opener.get_method = lambda: 'PUT' is some code I found on the web. It doesn't actually change the verb used to send the request, even though if you get_method it will reply with whatever you changed it to.

For example, in my case, because request contained data (not actually shown in example above) it sends a POST.

Angus Comber
  • 9,316
  • 14
  • 59
  • 107
  • http://stackoverflow.com/questions/111945/is-there-any-way-to-do-http-put-in-python You do `request.get_method` not `opener.get_method`. Although it is probably better to subclass `urllib2.Request` and overide `get_method()` – RedBaron Jul 25 '13 at 11:51