Skip to content

Instantly share code, notes, and snippets.

@yasuharu519
Created April 7, 2011 09:28
Show Gist options
  • Save yasuharu519/907410 to your computer and use it in GitHub Desktop.
Save yasuharu519/907410 to your computer and use it in GitHub Desktop.
this module was created to test googleURLShorter api http://code.google.com/intl/ja/apis/urlshortener/v1/getting_started.html
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import urllib2
import json
API_KEY = ""
class GoogleURLShorter(object):
def __init__(self, target_url, api_key=""):
self.baseUrl = 'https://www.googleapis.com/urlshortener/v1/url'
self.api_key = api_key
self.target_url = target_url
self.shortUrl = ''
def shortenURL(self):
query = {'longUrl' : self.target_url}
if not self.api_key == "":
query["key"] = self.api_key
encoded_query = json.dumps(query)
request = urllib2.Request(self.baseUrl, encoded_query)
request.add_header("Content-Type", "application/json")
response = urllib2.urlopen(request)
if response.msg == "OK":
response = json.loads(response.read())
self.shortUrl = response.get('id', None)
return self.shortUrl
def expandURL(self, target_url = ''):
if target_url == "":
target_url = self.shortUrl
if target_url == "":
raise Exception("URLをセットしてください。")
if not self.api_key == "":
response = urllib2.urlopen("%s?shortUrl=%s&key=%s" %
(self.baseUrl, target_url, self.api_key))
else:
response = urllib2.urlopen("%s?shortUrl=%s" %
(self.baseUrl, target_url))
if response.msg == "OK":
response = json.loads(response.read())
self.longUrl = response.get('longUrl', None)
return self.longUrl
if __name__ == '__main__':
test = GoogleURLShorter("http://d.hatena.ne.jp/yasuharu519/", API_KEY)
res = test.shortenURL()
print res
res = test.expandURL()
print res
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment