I am using urllib2 to submit data to a form. The problem is that the form responds with a 302 redirect. According to Python's HTTPRedirectHandler, the redirector will accept the request and convert it from POST to GET and follow 301 or 302. I would like to save the POST method and the data passed to the opener. I made an unsuccessful attempt in a custom HTTPRedirectHandler by simply adding data = req.get_data () to a new request.
I am sure that this was done earlier, so I thought I would make a message.
Note: this is similar to this post and this one , but I do not want to prevent redirection I just want to save the POST data.
Here is my HTTPRedirectHandler that doesn't work
class MyHTTPRedirectHandler(urllib2.HTTPRedirectHandler):
def redirect_request(self, req, fp, code, msg, headers, newurl):
"""Return a Request or None in response to a redirect.
This is called by the http_error_30x methods when a
redirection response is received. If a redirection should
take place, return a new Request to allow http_error_30x to
perform the redirect. Otherwise, raise HTTPError if no-one
else should try to handle this url. Return None if you can't
but another Handler might.
"""
m = req.get_method()
if (code in (301, 302, 303, 307) and m in ("GET", "HEAD")
or code in (301, 302, 303) and m == "POST"):
newurl = newurl.replace(' ', '%20')
return Request(newurl,
headers=req.headers,
data=req.get_data(),
origin_req_host=req.get_origin_req_host(),
unverifiable=True)
else:
raise HTTPError(req.get_full_url(), code, msg, headers, fp)
source
share