Created
April 29, 2011 21:27
-
-
Save pamelafox/949071 to your computer and use it in GitHub Desktop.
Shortening URLS using goo.gl
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
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