Skip to content

Instantly share code, notes, and snippets.

@eduardo-marcolino
Created July 30, 2013 13:53
Show Gist options
  • Save eduardo-marcolino/6113096 to your computer and use it in GitHub Desktop.
Save eduardo-marcolino/6113096 to your computer and use it in GitHub Desktop.
A Storage for Credentials that uses Redis
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""A Redis based Storage.
A Storage for Credentials that uses Redis.
"""
__author__ = 'eduardo.marcolino@gmail.com (Eduardo Marcolino)'
import threading
from oauth2client.client import Storage as BaseStorage
from oauth2client.client import Credentials
class Storage(BaseStorage):
"""
Usage:
import redis
from redis_storage import Storage
r = redis.StrictRedis(host='localhost', port=6379)
s = Storage(r, 'user1')
credentials = s.get()
"""
def __init__(self, redis_instance, user_key):
"""Constructor.
Args:
redis_instance: string, The name of the service under which the credentials
are stored.
user_key: string, The key of the user to store credentials for.
"""
self._redis_instance = redis_instance
self._user_key = user_key
self._lock = threading.Lock()
def acquire_lock(self):
"""Acquires any lock necessary to access this Storage.
This lock is not reentrant."""
self._lock.acquire()
def release_lock(self):
"""Release the Storage lock.
Trying to release a lock that isn't held will result in a
RuntimeError.
"""
self._lock.release()
def locked_get(self):
"""Retrieve Credential from redis.
Returns:
oauth2client.client.Credentials
"""
credentials = None
content = self._redis_instance.get(self._user_key)
if content is not None:
try:
credentials = Credentials.new_from_json(content)
credentials.set_store(self)
except ValueError:
pass
return credentials
def locked_put(self, credentials):
"""Set Credentials to redis.
Args:
credentials: Credentials, the credentials to store.
"""
self._redis_instance.set(self._user_key, credentials.to_json())
def locked_delete(self):
"""Delete Credentials empty.
Args:
credentials: Credentials, the credentials to store.
"""
self._redis_instance.set(self._user_key, '')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment