Skip to main content
 首页 » 编程设计

python之如果 Flask View 中出现错误,如何使 Redis 缓存对象失效或删除

2024年11月01日7fff_TT

我在使用 Flask 缓存模块时遇到一个问题,如果出现运行时错误,我不想缓存 View 。

谁能建议如何做到这一点?

这是我想要实现的目标。

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() 

关于在出现错误时如何停止缓存此 View 的任何想法?

请您参考如下方法:

您可以调用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()