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

- 启动文件:
app.py - 业务文件:
data.py - 缓存类库:
cache.py
现在问题是在 data.py 里调用了 cache.py 而 cache.py 为了初始化缓存插件使用了 current_app
from flask_caching import Cache as FlaskCachefrom 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 ?
回答:
app.py 文件里初始化:
from flask import Flaskfrom flask_caching import Cache
app = Flask(__name__)
cache = Cache(app, config=app.config['Cache'])
回答:
可以在Cache里添加一个方法
python">@classmethoddef init_app(cls,app,config):
cls.instance.init_app(app,config=config)
然后再app.py里
from cache import Cacheapp = Flask(___name__)
Cache.init_app(app,app.config['Cache'])
这样就不用从app导入Cache
以上是 Python Flask 获取全局配置 current_app 的问题如何解决? 的全部内容, 来源链接: utcz.com/p/938961.html

