Jay Taylor's notes

back to listing index

Per-Request After-Request Callbacks | Flask (A Python Microframework)

[web search]
Original source (flask.pocoo.org)
Tags: Flask async flask.pocoo.org
Clipped on: 2016-06-14

overview // docs // community // snippets // extensions

Per-Request After-Request Callbacks

Posted by Armin Ronacher on 2011-07-08 @ 11:21 and filed in Utilities

Flask provides the app.after_request function to trigger the execution of a function at the end of a request. This however is done for all requests. Sometimes it can be useful to trigger some code that modifies a response object only for one specific request.

For instance you might have some code that invalidates a cache somewhere and wants to update a cookie at the end of a request.

This can be easily implemented by keeping a list of callbacks on the g object:

from flask import g

def after_this_request(func):
    if not hasattr(g, 'call_after_request'):
        g.call_after_request = []
    g.call_after_request.append(func)
    return func


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

And here is how you can use it:

def invalidate_username_cache():
    @after_this_request
    def delete_username_cookie(response):
        response.delete_cookie('username')
        return response

This snippet by Armin Ronacher can be used freely for anything you like. Consider it public domain.

© Copyright 2010 - 2016 by Armin Ronacher