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

时间:2014-04-23 10:40:53

标签: python flask flask-cache

我正面临一个问题,我正在使用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()

如果我遇到错误,有关如何停止缓存此视图的任何想法?

1 个答案:

答案 0 :(得分:1)

您可以在cache.delete_memoized处理程序中调用after_this_request

# @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。所以你可以自己简单地引发错误并使用单独的处理程序处理异常:

@app.route('/myview')
@mycache.cached()
def process_view():
    try:
        return get_something()
    except Exception as e:
        raise ProcessViewIssue(e)

@app.errorhandler(ProcessViewIssue)
def handle_process_view_error(e):
    return print_error()