Created
November 27, 2012 12:19
-
-
Save TkTech/4153952 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
@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