3

I can make get or post request using urllib, but how do I make DELETE- and PUT-requests?

ndequeker
  • 7,932
  • 7
  • 61
  • 93
kevin
  • 4,177
  • 10
  • 32
  • 33

7 Answers7

7

The requests library can handle POST, PUT, DELETE, and all other HTTP methods, and is significantly less scary than urllib, httplib and their variants.

mikemaccana
  • 110,530
  • 99
  • 389
  • 494
4

You can override get_method with something like this:

def _make_request(url, data, method):
    request.urllib2.Request(url, data=data)
    request.get_method = lambda: method

Then you pass "DELETE" as method.

This answer covers the details.

Community
  • 1
  • 1
jsnklln
  • 81
  • 7
1

The method is set implicitly in the urlopen call

When you provide the data parameter a POST will be used.

urllib.request.urlopen(url, data=None[, timeout])

I don't think it's possible to use a DELETE HTTP method with urlib because of this line:

Request.get_method()
Return a string indicating the HTTP request method. This is only meaningful for HTTP requests, and currently always returns 'GET' or 'POST'.

Consider using httplib, httplib2, or Twisted instead .for better support of HTTP methods.

Brian R. Bondy
  • 339,232
  • 124
  • 596
  • 636
1

PUT request can be performed by httplib2

http://code.google.com/p/httplib2

yedpodtrzitko
  • 9,035
  • 2
  • 40
  • 42
1

http://twistedmatrix.com/documents/current/web/howto/client.html

If you're looking to work with HTTP in twisted using the client side I'd suggest checking that out. It demonstrates how you can really easily make a request using the agent class.

themaestro
  • 13,750
  • 20
  • 56
  • 75
1

As far as I know, urllib and urllib2 only support GET and POST requests. You should probably take a look at httplib or httplib2.

Luke404
  • 10,282
  • 3
  • 25
  • 31
  • Support for other methods in `urllib`has been added. [Doc](https://docs.python.org/3/library/urllib.request.html#urllib.request.Request) for that. – jar Nov 28 '18 at 13:58
0

The default HTTP methods in urllib library are POST and GET:

def get_method(self):
    """Return a string indicating the HTTP request method."""
    default_method = "POST" if self.data is not None else "GET"
    return getattr(self, 'method', default_method)

But we can override this get_method() function to get DELETE request:

req = urllib.request.Request(new_url)
req.get_method = lambda: "DELETE"
Kehe CAI
  • 1,161
  • 12
  • 18