Python Flask 获取全局配置 current_app 的问题如何解决?

  • 启动文件:app.py
  • 业务文件:data.py
  • 缓存类库:cache.py

现在问题是在 data.py 里调用了 cache.pycache.py 为了初始化缓存插件使用了 current_app

from flask_caching import Cache as FlaskCache
from flask import current_app


class Cache:
    instance = FlaskCache(current_app, config=current_app.config['Cache'])

    @classmethod
    def set(cls, key: str, value: str, timeout: int = 600):
        if not cls.instance.has(key):
            cls.instance.set(key, value, timeout=timeout)

    @classmethod
    def get(cls, key: str):
        return cls.instance.get(key)

但是就挂了:RuntimeError: Working outside of application context.

因为是中间隔了一层我用了 with app.app_context(): 也不行,请问要怎么解决?
难道必须要放在 app.py 初始化然后去 import cache from app

阅读 2.7k
2 个回答

app.py 文件里初始化:

from flask import Flask
from flask_caching import Cache

app = Flask(__name__)
cache = Cache(app, config=app.config['Cache'])

可以在Cache里添加一个方法

@classmethod
def init_app(cls,app,config):
    cls.instance.init_app(app,config=config)

然后再app.py里

from cache import Cache
app = Flask(___name__)
Cache.init_app(app,app.config['Cache']) 

这样就不用从app导入Cache

推荐问题
宣传栏