Redirect business again

.htaccess file has

Redirect 302 /index.html "http://localhost/new file.html"

But still when I do:

>>>obj = urllib2.urlopen("http://localhost/index.html")
>>>print obj.code()
200
>>>
Funny, what am I doing and why am I getting it this way? Figuring that out. Because the direct is happening transparently, one is not able to capture the redirect code.

If one needs to the capture redirect code, here is how it is done.


import urllib2

class SmartRedirectHandler(urllib2.HTTPRedirectHandler):
def http_error_302(self, req, fp, code, msg, headers):
result = urllib2.HTTPRedirectHandler.http_error_302(self, req, fp,code, msg,headers)

result.status = code
return result

request = urllib2.Request("http://localhost/index.html")
opener = urllib2.build_opener(SmartRedirectHandler())
obj = opener.open(request)
print 'I capture the http redirect code:', obj.status
print 'Its been redirected to:', obj.url


And the output from the session will be:


[06:59:14 senthil]$python smartredirecthandler.py
I capture the http redirect code: 302
Its been redirected to: http://localhost/new%20file.html

No comments: