blob: a243fd2ce35a28542100e5a09818f788b7b1e748 [file] [log] [blame]
Joe Gregorio9b57dd32011-02-17 15:53:50 -05001# Copyright 2010 Google Inc. All Rights Reserved.
2
3"""Utilities for OAuth.
4
Joe Gregorio825d78d2011-02-18 15:07:17 -05005Utilities for making it easier to work with OAuth 1.0 credentials.
Joe Gregorio9b57dd32011-02-17 15:53:50 -05006"""
7
8__author__ = 'jcgregorio@google.com (Joe Gregorio)'
9
10import pickle
Joe Gregorio560b5322011-02-22 11:09:24 -050011import threading
Joe Gregorio9b57dd32011-02-17 15:53:50 -050012
Joe Gregorioa0a52e42011-02-17 17:13:26 -050013from apiclient.oauth import Storage as BaseStorage
Joe Gregorio9b57dd32011-02-17 15:53:50 -050014
Joe Gregorioa0a52e42011-02-17 17:13:26 -050015
16class Storage(BaseStorage):
Joe Gregorio9b57dd32011-02-17 15:53:50 -050017 """Store and retrieve a single credential to and from a file."""
18
19 def __init__(self, filename):
20 self._filename = filename
Joe Gregorio560b5322011-02-22 11:09:24 -050021 self._lock = threading.Lock()
Joe Gregorio9b57dd32011-02-17 15:53:50 -050022
23 def get(self):
24 """Retrieve Credential from file.
25
26 Returns:
27 apiclient.oauth.Credentials
28 """
Joe Gregorio560b5322011-02-22 11:09:24 -050029 self._lock.acquire()
Joe Gregorio9b57dd32011-02-17 15:53:50 -050030 try:
31 f = open(self._filename, 'r')
32 credentials = pickle.loads(f.read())
33 f.close()
Joe Gregoriofffa7d72011-02-18 17:20:39 -050034 credentials.set_store(self.put)
Joe Gregorio9b57dd32011-02-17 15:53:50 -050035 except:
36 credentials = None
Joe Gregorio560b5322011-02-22 11:09:24 -050037 self._lock.release()
Joe Gregorio9b57dd32011-02-17 15:53:50 -050038
39 return credentials
40
41 def put(self, credentials):
42 """Write a pickled Credentials to file.
43
44 Args:
45 credentials: Credentials, the credentials to store.
46 """
Joe Gregorio560b5322011-02-22 11:09:24 -050047 self._lock.acquire()
Joe Gregorio9b57dd32011-02-17 15:53:50 -050048 f = open(self._filename, 'w')
49 f.write(pickle.dumps(credentials))
50 f.close()
Joe Gregorio560b5322011-02-22 11:09:24 -050051 self._lock.release()