一個比較簡單的 google shorten url 封裝.
用法和新版本可以查看我的 Github
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
| __author__ = "Zeuxis Lo <http: //studio.zeuik.com/>"
import urllib, urllib2
try: import json except ImportError, e: import simplejson as json
class GoogleUrlShort(object): api_url = "https://www.googleapis.com/urlshortener/v1/url"
def __init__(self, url): self.url = url def short(self, all_response = False): header = { "Content-Type": "application/json" } params = { "longUrl": self.url } try: response = urllib2.urlopen(urllib2.Request(self.api_url, json.dumps(params), header)) except urllib2.HTTPError, e: if e.code: response = e.fp json_data = response.read() if all_response is True: return json_data else: return json.loads(json_data)['id'] if "id" in json_data else "" def expend(self, all_response = False): json_data = urllib.urlopen("https://www.googleapis.com/urlshortener/v1/url?shortUrl=%s" % self.url).read() if all_response == True: return json_data else: return json.loads(json_data)['longUrl'] if "longUrl" in json_data else ""
def shorten(url, all_response = False): return GoogleUrlShort(url).short(all_response)
def expend(url, all_response = False): return GoogleUrlShort(url).expend(all_response)
|