flask: `@after_this_request` not working

半城伤御伤魂 提交于 2019-12-06 08:35:40

Make sure to import the decorator from flask.after_this_request. The decorator is new in Flask 0.9.

If you are using Flask 0.8 or older, then there is no specific after this request functionality. There is only a after every request hook, which is what the snippet coopts to handle per-request call-backs.

So unless you are using Flask 0.9 or newer you need to implement the documented hook yourself:

@app.after_request
def per_request_callbacks(response):
    for func in getattr(g, 'call_after_request', ()):
        response = func(response)
    return response

So that hook is run after each and every request, and looks for a list of hooks to call in g.call_after_request. The after_this_request decorator registers a function there.

Just import after_this_request from flask, you don't need to modify after_request or create a hook.

from flask import after_this_request

@after_this_request
def remove_file(response):
    print('After request ...')
    os.remove(filepath)
return response
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!