Question

I'm trying to make a put request via the urllib2 module of Python 2.7. When I perform a GET it works just fine but when I try to turn it into a PUT it returns me a 301 http error. My code is above :

opener = urllib2.build_opener(urllib2.HTTPHandler)
req = urllib2.Request(reqUrl)
base64string = base64.encodestring('%s:%s' % (v_username, v_password)).replace('\n', '')
req.add_header("Authorization", "Basic %s" % base64string)
req.add_header("Content-Type", "application/rdf+xml")
req.add_header("Accept", "application/rdf+xml")
req.add_header("OSLC-Core-Version", "2.0")
req.get_method = lambda: 'PUT'
req.allow_redirects=True
url = opener.open(req)

If I suppress the line

req.get_method = lambda: 'PUT'

it works but it's a get request (or a post if I pass some data) but it has to be a PUT and I don't how to do it differently with this module.

The error is

urllib2.HTTPError: HTTP Error 301: Moved Permanently.

Does anyone understand this more than I do? I'm quite a newbie with REST request and there are some specificity that remains obscure to me.

Was it helpful?

Solution

I'm not certain, but could it be that urllib is handling the 301 automatically for the GET but not for the PUT? According to the RFC, user agents can redirect GETs automatically, but not PUTs.

This page seems to suggest that urllib does indeed handle the 301 redirection automatically, and it seems plausible it wouldn't automatically handle the PUT redirect given the RFC. Guess you should find out what the redirect is to and redirect there.

OTHER TIPS

Thanks Ken F, you helped me understand the problem. I changed the handler directly in the urllib2.py file (not sure if it's very clean but whatever) so it can handle PUT requests:

if (code in (301, 302, 303, 307) and m in ("GET", "HEAD")
            or code in (301, 302, 303) and m in ("POST", "PUT")):

Indeed, when the request was neither GET nor POST, it automatically raised an error. I'm surprised I couldn't find anyone else with the same issue.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top