Skip to content

Instantly share code, notes, and snippets.

@logic
Created May 17, 2012 02:26
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save logic/2715756 to your computer and use it in GitHub Desktop.
Save logic/2715756 to your computer and use it in GitHub Desktop.
Adding an HTTP method to urllib2.Request.
import urllib2
class MethodRequest(urllib2.Request):
def __init__(self, *args, **kwargs):
if 'method' in kwargs:
self._method = kwargs['method']
del kwargs['method']
else:
self._method = None
return urllib2.Request.__init__(self, *args, **kwargs)
def get_method(self, *args, **kwargs):
if self._method is not None:
return self._method
return urllib2.Request.get_method(self, *args, **kwargs)
@logic
Copy link
Author

logic commented May 17, 2012

This addresses a small deficiency in urllib2: you can't specify an HTTP method to use, you can only say whether the request is a GET (by not specifying any data to send) or a POST (by specifying data). You can use this just like urllib2.Request, but you can also instantiate it with:

req = MethodRequest(url, method='PUT')

Now, when the actual request is made, the PUT HTTP method will be used, regardless of whether any data is supplied or not.

@hqqns
Copy link

hqqns commented Sep 18, 2015

Thanks, works a charm!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment