ismaelvc

shortener

Nov 25th, 2013
133
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.46 KB | None | 0 0
  1. from __future__ import print_function   # Adding also this to the module top.
  2. import sys
  3.  
  4.  
  5. # I would do it like this, for example:
  6.  
  7. '''
  8. Error handling code:
  9. Do you think compiling it is excessive? :)
  10. '''
  11. # error = compile("print('[!] Error: {0}'.format(e), file=sys.stderr)", '<string>', 'eval')
  12. error = "print('[!] Error: {0}'.format(e), file=sys.stderr)"
  13.  
  14.  
  15. class GoogleShortener(object):
  16.     """
  17. Based on:
  18. https://github.com/avelino/django-googl/blob/master/googl/short.py
  19. Googl Shortener Implementation
  20. Doesn't need anything from the app
  21. """
  22.     api_url = "https://www.googleapis.com/urlshortener/v1/url"
  23.  
  24.     def short(self, url):
  25.         params = json.dumps({'longUrl': url})
  26.         headers = {'content-type': 'application/json'}
  27.         response = requests.post(self.api_url, data=params,
  28.                                  headers=headers)
  29.         if response.ok:
  30.             try:
  31.                 data = response.json()
  32.                 self.shorten = data['id']
  33.                 return data['id']
  34.             except Exception, e:
  35.                 eval(error)
  36.  
  37.     def expand(self, url):
  38.         params = {'shortUrl': url}
  39.         response = requests.get(self.api_url, params=params)
  40.         if response.ok:
  41.             try:
  42.                 data = response.json()
  43.                 return data['longUrl']
  44.             except Exception, e:
  45.                 eval(error)
  46.  
  47.  
  48. # Of course if you know what kind of exceptions you get, you can be more explicit.
Advertisement
Add Comment
Please, Sign In to add comment