我正在使用 Flask 构建一个 Web 表单,并希望用户能够输入多个条目,并在将数据发送到数据库之前让他们有机会使用撤消按钮后悔输入。我正在尝试使用Flask-Caching,但没有设法正确设置它。
我已经按照Flask Mega-Tutorial设置 Flask(这是我的第一个 Flask 应用程序)。
+---app
| | forms.py
| | routes.py
| | __init__.py
| +---static
| +---templates
我想知道我需要如何配置 Flask 应用程序才能基本上能够做以下事情:
cache.add("variable_name", variable_data)
variable_name = cache.get("variable_name")
cache.clear()
在其中一个页面中(使用@app.route 装饰器的功能)?
在应用程序中。init .py 我有:
from flask import Flask
from config import Config
from flask_caching import Cache
app = Flask(__name__)
app.config.from_object(Config)
cache = Cache(app, config={'CACHE_TYPE': 'simple'})
from app import routes
在routes.py我有:
from flask import current_app
当我尝试调用缓存时,我使用下面的代码。
current_app.cache.add("variable_name", variable_data)
尝试使用表单时出现以下错误:
AttributeError: 'Flask' object has no attribute 'cache'
我发现的几乎所有教程都只是在同一个模块中包含应用程序声明和所有路由。但是当我在另一个模块中有路由时如何访问缓存?
为了在 中使用cache
对象routes.py
,您必须先导入它(从创建它的位置,即app/__init__.py
):
from app import cache
然后使用它:
cache.add("variable_name", variable_data)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句