在从互联网上拼凑了很多东西之后,我终于得到了这个解决方案,用于在使用应用程序工厂功能构建的应用程序中使用 Flask-Caching 显式缓存数据。布局和应用程序工厂设置遵循 Flask 教程。
(在我的特定用例中,我使用的是 Google Calendar API,并希望缓存为连接和身份验证而构建的服务以及查询结果。每次用户与页面交互时都无需重新查询。)
我的烧瓶应用程序的缩写视图:
/.../mysite/
|--- mysite_flask/
| |--- __init__.py (application factory)
| |--- cache.py (for the flask_caching extension)
| |--- site.py (a blueprint, views, and related functions)
__init__.py:
from flask import Flask
def create_app(test_config=None):
# create and configure app as desired
app = Flask(__name__, instance_relative_config=True)
app.config.from_mapping(
...
)
# check whether testing and for instance folder
...
# importing and initializing other blueprints and views
...
# import site blueprint, views, and functionality
from . import site
app.register_blueprint(site.bp)
app.add_url_rule('/', endpoint='index')
# Extensions
# import cache functionality
from .cache import cache
cache.init_app(app)
return app
缓存.py
from flask_caching import Cache
cache = Cache(config={'CACHE_TYPE': 'SimpleCache'})
网站.py
# Other required imports
...
from .cache import cache
bp = Blueprint('site', __name__)
# other views and functions
...
@bp.route('/book', methods=('GET', 'POST'))
def book():
# Connect to calendar or fail gracefully
service = cache.get("service") # now the cache is available within a view
if service is None: # service hasn't been added to cache or is expired
try: # rebuild the service to connect to calendar
service = connectToCalendar() # uses google.oauth2 and googleapiclient.discovery
cache.set("service", service) # store service in cache
g.error = False
except Exception as e:
flash(e)
g.error = True
return render_template('site/book.html') # jinja2 template that checks for g.error
# remaining logic for the 'book' view
...
# Cache results of queries
if cache.get("week_{}".format(offset)) is None:
# get new results
week = getWeek(service)
cache.set("week_{}".format(offset), week)
else:
week = cache.get("week_{}".format(offset))
return render_template('site/book.html', <...arguments...>)