Skip to content

Instantly share code, notes, and snippets.

@TkTech
Created November 27, 2012 12:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TkTech/4153952 to your computer and use it in GitHub Desktop.
Save TkTech/4153952 to your computer and use it in GitHub Desktop.
@classmethod
def shorten(cls, url):
# Make sure the URL hasn't already been shortened, since github
# may does this in the future for web hooks. Better safe than silly.
if re.search(r'^https?://git.io', url):
return url
# Only github URLs can be shortened by the git.io service, which
# will return a 201 created on success and return the new url
# in the Location header.
try:
r = requests.post('http://git.io', data={
'url': url
}, timeout=4.0)
except requests.exceptions.Timeout:
return url
# Something went wrong, usually means we're being throttled.
# TODO: If we are being throttled, handle this smarter instead
# of trying again on the next message.
if r.status_code != 201:
return url
return r.headers['Location']
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment