kevin
kevin

Reputation: 4367

how to make a delete / put request in python

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

Upvotes: 3

Views: 13089

Answers (7)

Kehe CAI
Kehe CAI

Reputation: 1231

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"

Upvotes: 0

jsnklln
jsnklln

Reputation: 91

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.

Upvotes: 5

mikemaccana
mikemaccana

Reputation: 123500

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

Upvotes: 7

Brian R. Bondy
Brian R. Bondy

Reputation: 347486

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.

Upvotes: 1

Luke404
Luke404

Reputation: 10620

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

Upvotes: 1

themaestro
themaestro

Reputation: 14256

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.

Upvotes: 1

yedpodtrzitko
yedpodtrzitko

Reputation: 9359

PUT request can be performed by httplib2

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

Upvotes: 1

Related Questions