Created
December 22, 2009 02:37
-
-
Save anarchivist/261451 to your computer and use it in GitHub Desktop.
Use the ln-s.net URL shortening service
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
#!/usr/bin/env python | |
"""ln_s.py: Use the ln-s.net URL redirector | |
Mark Matienzo - October 2007""" | |
import getopt, re, sys, urllib, urllib2 | |
_api_url = 'http://ln-s.net/home/api.jsp' | |
_help_msg = 'For help, use, -h or --help' | |
_invalid_url = 'Invalid URL (must start with either "http://" or "https://")' | |
def main(): | |
"""usage: ln_s.py <url>""" | |
try: | |
opts, args = getopt.getopt(sys.argv[1:], "h", ["help"]) | |
except getopt.error, e: | |
print e | |
print _help_msg | |
sys.exit(2) | |
for o, a in opts: | |
if o in ("-h", "--help"): | |
print main.__doc__ | |
sys.exit(0) | |
try: | |
print shorten(sys.argv[1]) | |
sys.exit(1) | |
except IndexError, e: | |
raise IOError, 'Missing URL - %s' % _help_msg | |
sys.exit(2) | |
def shorten(url_to_shorten): | |
"""shorten(): Creates shortened redirect using ln-s.net's API | |
Returns a string or throws an exception. For more information on | |
the ln-s.net API, see http://ln-s.net/home/apidoc.jsp. | |
N.B.: ln-s.net doesn't return proper HTTP error codes (just 200). | |
""" | |
try: | |
params = urllib.urlencode({'url': url_to_shorten.strip()}) | |
shorten_req = urllib2.Request(url=_api_url, data=params) | |
opened = urllib2.urlopen(shorten_req) | |
result = opened.read().strip() | |
if result.startswith('200 '): | |
return result[4:] | |
else: | |
raise IOError, result | |
except (AttributeError, TypeError), e: | |
raise TypeError, '%s\n%s' % (e, _invalid_url) | |
if __name__ == "__main__": | |
sys.exit(main()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment