Tracking redirection of the request using request history

Sometimes the URL that we are accessing may have been moved or it might get redirected to some other location. We can track them using Requests. The response object's history property can be used to track the redirection. Requests can accomplish location redirection with every verb except with HEAD. The Response.history list contains the objects of the Requests that were generated in order to complete the request.

>>> r = requests.get('http:google.com')
>>> r.url
u'http://www.google.co.in/?gfe_rd=cr&ei=rgMSVOjiFKnV8ge37YGgCA'
>>> r.status_code
200
>>> r.history
(<Response [302]>,)

In the preceding example, when we tried sending a request to 'www.google.com', we got the r.history value as 302 which means the URL has been redirected to some other location. The r.url shows us the proof here, with the redirection URL.

If we don't want Requests to handle redirections, or if we are using POST, GET, PUT, PATCH, OPTIONS, or DELETE, we can set the value of allow_redirects=False, so that redirection handling gets disabled.

>>> r = requests.get('http://google.com', allow_redirects=False)
>>> r.url
u'http://google.com/'
>> r.status_code
302
>>> r.history
[ ]

In the preceding example, we used the parameter allow_redirects=False, which resulted the r.url without any redirection in the URL and the r.history as empty.

If we are using the head to access the URL, we can facilitate redirection.

>>> r = requests.head('http://google.com', allow_redirects=True)
>>> r.url
u'http://www.google.co.in/?gfe_rd=cr&ei=RggSVMbIKajV8gfxzID4Ag'
>>> r.history
(<Response [302]>,)

In this example, we tried accessing the URL with head and the parameter allow_redirects enabled which resulted us the URL redirected.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.70.38