如果Flask vi中出现错误,如何使redis缓存对象失效或删除

2024-06-09 05:09:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我面临一个问题,我正在使用Flask缓存模块,如果我有一个运行时错误,我不想缓存视图。在

有人能建议怎么做吗?在

这就是我想要达到的目标。在

from flask import Flask    
from flask.ext.cache import Cache

app = Flask(__name__)
mycache = Cache()
mycache.init_app(app)

@mycache.cached()
@app.route('/myview')
def process_view():
    try:
        return get_something()
    except:
        return print_error_and_no_cache_this_view()

如果有错误,如何停止缓存这个视图?在


Tags: 模块fromimportview视图appflaskcache
1条回答
网友
1楼 · 发布于 2024-06-09 05:09:24

您可以在^{}处理程序中调用^{}

# @cached needs to be invoked before @route
# because @route registers the handler with Flask
# and @cached returns a different function.
# If you @route first and then @cache Flask will
# always execute the *uncached* version.

@app.route('/myview')
@mycache.cached()
def process_view():
    try:
        return get_something()
    except:

        @app.after_this_request
        def clear_cache(response):
            mycache.delete_memoized('process_view')
            return response

        return print_error_and_no_cache_this_view() 

或者,查看Flask Cache的代码,它看起来是does not handle errors thrown by the view。因此,可以自己提出错误,并使用单独的处理程序处理异常:

^{pr2}$

相关问题 更多 >