Created
December 18, 2012 01:40
-
-
Save cbare/4324237 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| ## Demonstrate following redirects with POST using urllib2. | |
| ## | |
| ## Note: This is an experiment and may not be the best way | |
| ## to go about doing this. For example, why not just | |
| ## change the endpoints and issue a new request? Do | |
| ## we really want to be redirected on every request? | |
| ############################################################ | |
| import urllib2 | |
| import json | |
| ## modify the behavior of urllib2's HTTPRedirectHandler | |
| class HackedHTTPRedirectHandler(urllib2.HTTPRedirectHandler): | |
| def redirect_request(self, req, fp, code, msg, headers, newurl): | |
| """Hack HTTPRedirectHandler to follow redirected POST requests by POSTing to the new location | |
| """ | |
| m = req.get_method() | |
| if (code in (301, 302, 303, 307)): | |
| # Strictly (according to RFC 2616)... | |
| # ... Damn the RFC! Follow those redirects!!! - jcb | |
| # be conciliant with URIs containing a space | |
| newurl = newurl.replace(' ', '%20') | |
| return urllib2.Request(newurl, | |
| data=req.data, | |
| headers=req.headers, | |
| origin_req_host=req.get_origin_req_host(), | |
| unverifiable=True) | |
| else: | |
| raise urllib2.HTTPError(req.get_full_url(), code, msg, headers, fp) | |
| ## this endpoint doesn't redirect | |
| endp_prod = "https://auth-prod.sagebase.org/auth/v1" | |
| ## this endpoint redirects | |
| endp_dev = "https://auth-dev.sagebase.org/auth/v1" | |
| ## headers | |
| h = {'Content-Type':'application/json', 'Accept':'application/json'} | |
| ## the payload: insert valid credentials here | |
| d = {"password": "secret", "email": "[email protected]"} | |
| ## make request with new Redirect Handler | |
| req = urllib2.Request(url=endp_dev + "/session", data=json.dumps(d), headers=h) | |
| opener = urllib2.build_opener(HackedHTTPRedirectHandler()) | |
| f = opener.open(req) | |
| ans = json.loads(f.read()) | |
| ## if this works, you're logged in! | |
| print "Session token = %s\n" % (ans['sessionToken'],) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment