如何在带参数的Flask路由上用flask-cache缓存全部数据库结果?
问题
我有一个从数据库获取数据的Flask应用,想通过缓存避免频繁请求数据库。目前用flask_caching实现缓存,但缓存只对单个请求的文档生效——数据库里有1000条数据,我希望缓存所有数据,而不是当前请求对应的单条,问题出在请求URL包含doc_id参数。
原路由代码如下:
@site.route('/display/<doc_id>', methods=["GET", "POST"]) @cache.cached(query_string=True) def display(doc_id): results = connect_to_db_get_ALL_results() return render_template("display.html")
现在的问题是:缓存仅针对特定文档生效。比如访问http://localhost/display/1后,再跳转到http://localhost/display/2时,会重新从数据库拉取数据并缓存;回到http://localhost/display/1时才会读缓存。但connect_to_db_get_ALL_results()实际返回的是所有文档的数据,我希望不管访问哪个doc_id,都能直接从缓存读取全量数据。试过query_string参数、memoize装饰器,也尝试过缓存返回全量结果的函数,但都没效果。
解决方法
核心是缓存返回全量结果的函数,而非路由。修改后的代码如下:
@site.route('/display/<doc_id>', methods=["GET", "POST"]) def display(doc_id): results = connect_to_db_get_ALL_results() return render_template("display.html") @cache.cached(timeout=500, key_prefix='all_docs') def connect_to_db_get_ALL_results(): <从数据库表获取数据的代码>
内容的提问来源于stack exchange,提问作者Calamari
相关产品推荐
相关产品推荐

