Skip to content

Instantly share code, notes, and snippets.

@pamelafox
Created April 29, 2011 21:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save pamelafox/949071 to your computer and use it in GitHub Desktop.
Save pamelafox/949071 to your computer and use it in GitHub Desktop.
Shortening URLS using goo.gl
import cgi
import urllib, urllib2
import logging
from django.utils import simplejson
class Googl():
def __init__(self, api_key):
self.api_key = api_key
self.base_url = 'https://www.googleapis.com/urlshortener/v1/url?key=%s' % self.api_key
def shorten(self, long_url):
try:
post_params = {'longUrl': long_url}
request = urllib2.Request(url=self.base_url, data=simplejson.dumps(post_params))
request.add_header('Content-type', 'application/json')
response = urllib2.urlopen(request)
json = simplejson.loads(response.read())
short_url = json['id']
return short_url
except urllib2.HTTPError, e:
logging.info('Error shortening: %s' % e.read())
return None
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment