This file contains 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
import httplib, urlparse | |
def resolve_http_redirect(url, depth=10): | |
""" | |
>>> resolve_http_redirect('http://localhost:8080/share') | |
'http://localhost:8080/share/page/' | |
""" | |
o = urlparse.urlparse(url) | |
connection = httplib.HTTPConnection(o.netloc) | |
connection.request('GET', o.path) | |
response = connection.getresponse() | |
location = response.getheader('location') | |
if response.status == httplib.FOUND and location != None: | |
return resolve_http_redirect(location) | |
elif response.status == httplib.OK: | |
return url | |
if __name__ == '__main__': | |
print(resolve_http_redirect('http://localhost:8080/share')) |
โค้ดดังกล่าวแก้ปัญหาได้ด้วย recursive โดยให้มันตรวจสอบไปเรื่อยๆ ว่า status code ที่ได้เป็น 302 หรือไม่ ถ้าเป็น 200 แล้วก็ให้คืน URL นี้มาได้เลย
No comments :
Post a Comment