Skip to content

Instantly share code, notes, and snippets.

@thiagopnobre
Last active August 29, 2015 14:14
Show Gist options
  • Save thiagopnobre/31ff07112ef4961d0c20 to your computer and use it in GitHub Desktop.
Save thiagopnobre/31ff07112ef4961d0c20 to your computer and use it in GitHub Desktop.
Algoritmo para desencurtar URLs obtido do stackoverflow seguido da refatoração que fiz.
# Código original
import httplib
import urlparse
def unshorten_url(url):
parsed = urlparse.urlparse(url)
h = httplib.HTTPConnection(parsed.netloc)
resource = parsed.path
if parsed.query != "":
resource += "?" + parsed.query
h.request('HEAD', resource)
response = h.getresponse()
if response.status/100 == 3 and response.getheader('Location'):
# changed to process chains of short urls
return unshorten_url(response.getheader('Location'))
else:
return url
# Código refatorado
from urlparse import urlparse
from httplib import HTTPSConnection, HTTPConnection
def unshorten_url(url):
parsed_url = urlparse(url)
if parsed_url.scheme == 'https':
host = HTTPSConnection(parsed_url.netloc)
else:
host = HTTPConnection(parsed_url.netloc)
resource = parsed_url.path
if parsed_url.query:
resource = '?'.join((resource, parsed_url.query))
host.request('HEAD', resource)
response = host.getresponse()
location = response.getheader('Location')
if response.status/100 == 3 and location:
return unshorten_url(location)
else:
return url
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment