Sometime there is some code that you would like to run after the requests was served. The after_request hook can help you in this, thoigh beware, it won't run in the rare (well, hopefully rare) cases when there is an uncaught exception in the route.


from flask import Flask, abort
import datetime

app = Flask(__name__)

def after_request(response):"after_request")
    return response

def main():"main route")
    return "Hello " + str(

def crash():"crash route")
    a = 0
    b = 3 / a

Run as:

FLASK_APP=app FLASK_DEBUG=1 flask run

Output on the console:

[2020-06-23 13:21:22,699] INFO in app: main route
[2020-06-23 13:21:22,699] INFO in app: after_request - - [23/Jun/2020 13:21:22] "GET / HTTP/1.1" 200 -

Visiting the http://localhost:5000/crash URL shows a stack trace like this:

[2020-06-23 13:21:11,582] INFO in app: crash route - - [23/Jun/2020 13:21:11] "GET /crash HTTP/1.1" 500 -
Traceback (most recent call last):
  File "/home/gabor/work/", line 20, in crash
    b = 3 / a
ZeroDivisionError: division by zero