美文网首页
Flask 封装一个Redis插件

Flask 封装一个Redis插件

作者: 深吸一口气 | 来源:发表于2021-06-18 17:41 被阅读0次

    可参考Flask官方文档中的扩展开发

    redis_client.py

    import redis
    from flask import current_app, _app_ctx_stack
    
    
    class RedisClient():
    
        def __init__(self, app=None):
            self.app = app
            if app is not None:
                self.init_app(app)
    
        def init_app(self, app):
            app.config.setdefault('REDIS_HOST', '127.0.0.1')
            app.config.setdefault('REDIS_PORT', 6379)
            app.config.setdefault('REDIS_PASSWORD', '')
    
        def connect(self):
            pool = redis.ConnectionPool(
                host=current_app.config["REDIS_HOST"],
                port=current_app.config["REDIS_PORT"],
                password=current_app.config["REDIS_PASSWORD"]
            )
            return redis.StrictRedis(connection_pool=pool)
    
        @property
        def connection(self):
            ctx = _app_ctx_stack.top
            if ctx is not None:
                if not hasattr(ctx, 'redis_db'):
                    ctx.redis_db = self.connect()
                return ctx.redis_db
    
        def set(self, key, value, ex):
            self.connection.set(key, value, ex=ex)
    
        def get(self, key):
            value = self.connection.get(key)
            if value:
                value = value.decode("utf-8")
            return value
    
    redis_client = RedisClient()
    

    使用

    from redis_client import RedisClient
    from flask import Flask
    
    def create_app():
        app = Flask(__name__)
        # config里需要配置redis参数REDIS_HOST、REDIS_PORT、REDIS_PASSWORD
        redis_client.init_app(app)
    
        return app
    

    相关文章

      网友评论

          本文标题:Flask 封装一个Redis插件

          本文链接:https://www.haomeiwen.com/subject/znyzeltx.html