Package flickyou :: Package backend :: Module utils

Source Code for Module flickyou.backend.utils

 1  import md5 
 2  import os 
 3  import webbrowser 
 4   
 5  BASE_HOST = 'flickr.com' 
 6  REST_API_PATH = '/services/rest' 
 7  AUTH_API_PATH = '/services/auth' 
 8   
 9  REST_API_URL = 'http://%s%s/' % (BASE_HOST, REST_API_PATH) 
10  AUTH_API_URL = 'http://%s%s/' % (BASE_HOST, AUTH_API_PATH) 
11   
12  UPLOAD_URL = 'http://api.flickr.com/services/upload/' 
13   
14 -def get_api_signature(secret_key, **params):
15 """API signing, see: <http://www.flickr.com/services/api/auth.spec.html>""" 16 keys = params.keys() 17 keys.sort() 18 19 lst = [] 20 for key in keys: 21 lst.append("%s%s" % (str(key), str(params[key]))) 22 lst.insert(0, secret_key) 23 sig = ''.join(lst) 24 return md5.new(sig).hexdigest()
25
26 -def open_url_in_browser(url):
27 try: 28 webbrowser.open(url) 29 except: 30 controller = webbrowser.get('macosx') 31 controller.open(url)
32 33
34 -class TokenCache(object):
35 """Represents the cache of the token. 36 37 It stores on the file system."""
38 - def __init__(self, api_key, base_path=os.path.expanduser('~')):
39 self._api_key = api_key 40 self.base_path = base_path 41 self._token = None
42
43 - def get(self):
44 """Gets the token from the cache.""" 45 if not self._token: 46 self._token = self._read_token_from_file() 47 return self._token
48
49 - def put(self, token):
50 """Puts a new token in the cache overwriting the old one if any.""" 51 self._token = token 52 self._write_token_to_file(self._token)
53
54 - def _get_cache_path(self):
55 return os.path.join(self.base_path, '.flickyou', self._api_key)
56
57 - def _get_cache_filename(self):
58 return os.path.join(self._get_cache_path(), 'token')
59
60 - def _read_token_from_file(self):
61 f = None 62 try: 63 try: 64 f = open(self._get_cache_filename(), 'r') 65 return f.read().strip() 66 except (IOError, OSError): 67 return None 68 finally: 69 if f: 70 f.close()
71
72 - def _write_token_to_file(self, token):
73 if not os.path.exists(self._get_cache_path()): 74 os.makedirs(self._get_cache_path()) 75 76 f = open(self._get_cache_filename(), 'w') 77 f.write(token) 78 f.write("\n") 79 f.close()
80