Skip to content

Instantly share code, notes, and snippets.

@masahitojp
Created October 22, 2010 04:31
Show Gist options
  • Save masahitojp/639939 to your computer and use it in GitHub Desktop.
Save masahitojp/639939 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 改変前ソース
# Pythonを使ってgoo.glの短縮URLを得る | TRIVIAL TECHNOLOGIES on CLOUD
# http://coreblog.org/ats/pythonic-way-of-obtaining-shorten-url-by-using-goo_gl
def google_shorten(url):
from re import match
from urllib2 import urlopen, Request, HTTPError, quote
try:
from json import loads
except ImportError:
try:
from simplejson import loads
except ImportError:
# Google Appengine offers simplejson via django
from django.utils import simplejson as json
try:
req=Request('http://goo.gl/api/url',
'url=%s'%quote(url), {'User-Agent':'toolbar'})
r=urlopen(req)
j = loads(r.read())
return j['short_url']
except HTTPError, e:
raise Exception('Unknown eror forming short URL.')
if __name__ == '__main__':
from sys import argv
print google_shorten(argv[1])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment