1# Copyright 2016 Google Inc. All rights reserved. 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. 14 15"""Dictionary storage for OAuth2 Credentials.""" 16 17from oauth2client import client 18 19 20class DictionaryStorage(client.Storage): 21 """Store and retrieve credentials to and from a dictionary-like object. 22 23 Args: 24 dictionary: A dictionary or dictionary-like object. 25 key: A string or other hashable. The credentials will be stored in 26 ``dictionary[key]``. 27 lock: An optional threading.Lock-like object. The lock will be 28 acquired before anything is written or read from the 29 dictionary. 30 """ 31 32 def __init__(self, dictionary, key, lock=None): 33 """Construct a DictionaryStorage instance.""" 34 super(DictionaryStorage, self).__init__(lock=lock) 35 self._dictionary = dictionary 36 self._key = key 37 38 def locked_get(self): 39 """Retrieve the credentials from the dictionary, if they exist. 40 41 Returns: A :class:`oauth2client.client.OAuth2Credentials` instance. 42 """ 43 serialized = self._dictionary.get(self._key) 44 45 if serialized is None: 46 return None 47 48 credentials = client.OAuth2Credentials.from_json(serialized) 49 credentials.set_store(self) 50 51 return credentials 52 53 def locked_put(self, credentials): 54 """Save the credentials to the dictionary. 55 56 Args: 57 credentials: A :class:`oauth2client.client.OAuth2Credentials` 58 instance. 59 """ 60 serialized = credentials.to_json() 61 self._dictionary[self._key] = serialized 62 63 def locked_delete(self): 64 """Remove the credentials from the dictionary, if they exist.""" 65 self._dictionary.pop(self._key, None) 66