示例#1
0
文件: core.py 项目: valency/quickauth
class QuickAuth:
    def __init__(self, dbfile='auth.db'):
        self.conn = Redis(dbfile)

    def register(self, key=None):
        if key is None:
            key = str(uuid1(clock_seq=int(datetime.now().timestamp())))
        value = str(uuid4())
        if self.conn.set(key, value):
            return {
                'key': key,
                'secret': value
            }
        else:
            raise ValueError('write to database failed: {} = {}'.format(key, value))

    def authorize(self, key, value):
        c = self.conn.get(key)
        if c is not None:
            return c.decode() == value
        return False

    def update(self, key):
        if self.conn.get(key):
            return self.register(key=key)
        else:
            raise ValueError('key is not found: {}'.format(key))
class RedisClient:

    conn = ""
    CHANNEL = "key-update"
    pubsub = ""

    def __init__(self, db_path):
        os.makedirs(os.path.dirname(db_path), exist_ok=True)

        try:
            if not self.conn:
                self.conn = Redis(db_path)
        except:
            raise Exception("Unable to create connection with Redis server")

    def get_key(self, key):
        return self.conn.get(key)

    def set_key(self, key, value, publish_update=False):
        if publish_update:
            self.publish_update(message=json.dumps({key: value}))

        return self.conn.set(key, value)

    def remove_key(self, key):
        return self.conn.delete(key)

    def publish_update(self, channel=CHANNEL, message=""):
        self.conn.pubsub()
        self.conn.publish(channel, message)

    def get_update(self, channel=CHANNEL):
        if not self.pubsub:
            self.pubsub = self.conn.pubsub()
            self.pubsub.subscribe(channel)

        return self.pubsub.get_message(channel)
示例#3
0
class RedisStore(DataStore):
    """Implementation of Redis datastore"""
    def __init__(self):
        super().__init__()
        if config.settings.stackl_redis_type == "fake":
            logger.info("Using fake client")

            self.redis = Redis()
        else:
            self.redis = redis.Redis(
                host=config.settings.stackl_redis_host,
                port=config.settings.stackl_redis_port,
                password=config.settings.stackl_redis_password,
                db=0)

    def get(self, **keys):
        """Gets a document from a redis instance"""
        document_key = keys.get("category") + '/' + keys.get(
            "type") + '/' + keys.get("name")
        logger.debug(f"[RedisStore] get on key '{document_key}'")

        redis_value = self.redis.get(document_key)
        if redis_value is None:
            response = self._create_store_response(
                status_code=StatusCode.NOT_FOUND, content={})
        else:
            content = json.loads(self.redis.get(document_key))
            response = self._create_store_response(status_code=StatusCode.OK,
                                                   content=content)
        logger.debug(f"[RedisStore] StoreResponse for get: {response}")
        return response

    def get_all(self, category, document_type, wildcard_prefix=""):
        """Gets all documents of a type from a Redis"""
        document_key = f"{category}/{document_type}/{wildcard_prefix}*"
        logger.debug(
            f"[RedisStore] get_all in '{document_key}' for type '{document_type}'"
        )
        content = []
        for key in self.redis.scan_iter(document_key):
            content.append(json.loads(self.redis.get(key)))
        response = self._create_store_response(status_code=StatusCode.OK,
                                               content=content)
        logger.debug(f"[RedisStore] StoreResponse for get: {response}")
        return response

    def get_history(self, category, document_type, name):
        """Gets the snapshots of document from Redis"""
        document_key = category + '/' + document_type + '/' + name
        logger.debug(
            f"[RedisStore] get_history in '{document_key}' for type '{document_type}'"
        )
        content = []
        for key in self.redis.scan_iter(document_key):
            content.append(json.loads(self.redis.get(key)))
        response = self._create_store_response(status_code=StatusCode.OK,
                                               content=content)
        logger.debug(f"[RedisStore] StoreResponse for get: {response}")
        return response

    def put(self, file):
        """Puts a document in Redis"""
        document_key = file.get("category") + '/' + file.get(
            "type") + '/' + file["name"]
        logger.debug(f"[RedisStore] put on '{document_key}' with file {file}")
        self.redis.set(document_key, json.dumps(file))
        response = self._create_store_response(
            status_code=StatusCode.CREATED,
            content=json.loads(self.redis.get(document_key)))
        logger.debug(f"[RedisStore] StoreResponse for put: {response}")
        return response

    def delete(self, **keys):
        """Deletes a document in Redis"""
        document_key = keys.get("category") + '/' + keys.get(
            "type") + '/' + keys.get("name")
        self.redis.delete(document_key)
        response = self._create_store_response(status_code=200, content={})
        logger.debug(f"[RedisStore] StoreResponse for delete: {response}")
        return response
示例#4
0
#!/usr/bin/python3
# encoding: utf-8
# @Time    : 2021/8/24 13:56
# @author  : zza
# @Email   : [email protected]
# @File    : demo_redislite.py
from redislite import Redis
redis_connection = Redis('./redis.db')
redis_connection.keys()
[]
redis_connection.set('key', 'value')
True
redis_connection.get('key')
'value'