blob: ed1a18c290fdaa5aacff8a6d69d08fa65b538701 [file] [log] [blame]
Joe Gregorio20a5aa92011-04-01 17:44:25 -04001# Copyright (C) 2010 Google Inc.
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
Joe Gregorio9b57dd32011-02-17 15:53:50 -050014
15"""Utilities for OAuth.
16
Joe Gregorio825d78d2011-02-18 15:07:17 -050017Utilities for making it easier to work with OAuth 1.0 credentials.
Joe Gregorio9b57dd32011-02-17 15:53:50 -050018"""
19
20__author__ = 'jcgregorio@google.com (Joe Gregorio)'
21
22import pickle
Joe Gregorio560b5322011-02-22 11:09:24 -050023import threading
Joe Gregorio9b57dd32011-02-17 15:53:50 -050024
Joe Gregorioa0a52e42011-02-17 17:13:26 -050025from apiclient.oauth import Storage as BaseStorage
Joe Gregorio9b57dd32011-02-17 15:53:50 -050026
Joe Gregorioa0a52e42011-02-17 17:13:26 -050027
28class Storage(BaseStorage):
Joe Gregorio9b57dd32011-02-17 15:53:50 -050029 """Store and retrieve a single credential to and from a file."""
30
31 def __init__(self, filename):
32 self._filename = filename
Joe Gregorio560b5322011-02-22 11:09:24 -050033 self._lock = threading.Lock()
Joe Gregorio9b57dd32011-02-17 15:53:50 -050034
35 def get(self):
36 """Retrieve Credential from file.
37
38 Returns:
39 apiclient.oauth.Credentials
40 """
Joe Gregorio560b5322011-02-22 11:09:24 -050041 self._lock.acquire()
Joe Gregorio9b57dd32011-02-17 15:53:50 -050042 try:
43 f = open(self._filename, 'r')
44 credentials = pickle.loads(f.read())
45 f.close()
Joe Gregoriofffa7d72011-02-18 17:20:39 -050046 credentials.set_store(self.put)
Joe Gregorio9b57dd32011-02-17 15:53:50 -050047 except:
48 credentials = None
Joe Gregorio560b5322011-02-22 11:09:24 -050049 self._lock.release()
Joe Gregorio9b57dd32011-02-17 15:53:50 -050050
51 return credentials
52
53 def put(self, credentials):
54 """Write a pickled Credentials to file.
55
56 Args:
57 credentials: Credentials, the credentials to store.
58 """
Joe Gregorio560b5322011-02-22 11:09:24 -050059 self._lock.acquire()
Joe Gregorio9b57dd32011-02-17 15:53:50 -050060 f = open(self._filename, 'w')
61 f.write(pickle.dumps(credentials))
62 f.close()
Joe Gregorio560b5322011-02-22 11:09:24 -050063 self._lock.release()