This article is participating in Python Theme Month. See the link to the event for more details


The introduction

During the interaction between the client and the server, there are some preparations or finalizations that need to be handled, such as:

  • At the start of the request, a database connection is established
  • Login permission authentication is performed at the start of the request
  • At the end of the request, specify the interactive format of the data

Flask provides the functionality of a common facility, the request hook, in order to keep each view function from having to code repetitive functions.


Flask Request hook

Flask supports four types of request hooks:

  • before_first_request: Is executed before the first request is processed
  • before_request: Executed before each request. If a response is returned in a decorated function, the view function is no longer called
  • after_request: Is executed after each request is processed
    • Takes one argument: the response of the view function
    • In this function, you can make the final modification to the response value before returning it
    • The response in the parameter needs to be returned in this parameter
  • teardown_request: Executed after each request, taking one parameter: error message
    • You need to run in non-mode mode


The test code

""" Author: Hui Desc: {know Flask request hooks} """
from flask import Flask

app = Flask(__name__)


@app.route("/index")
def index() :
    print("index called")
    a = 1 / 0
    response = '{"name": "hui"}'
    return response


@app.route("/hello")
def hello() :
    print("hello called")
    return {'welcome': 'hello'}


@app.before_first_request
def handle_before_first_request() :
    Is executed before the first request is processed
    print("handle_before_first_request called")


@app.before_request
def handle_before_request() :
    "" is executed before each request is processed """
    print("handle_before_request called")


@app.after_request
def handle_after_request(response) :
    Param response: response returned by the view function after processing. """
    print("handle_after_request called")
    # Specifies the response return format type as JSON
    # response.headers['Content-Type'] = 'application/json'
    print(response)
    return response


@app.teardown_request
def handle_teardown_request(errors) :
    """ param: errors: server error information, if there is no error, None """
    print("handle_teardown_request called")
    print(errors)


if __name__ == "__main__":
    app.run()

Copy the code


To access/hello first

Start the program, go to http://127.0.0.1:5000/hello first

Look at the output of PyCharm

handle_before_first_request called	# When the Web application first requests

handle_before_request called	# before each request

hello called	# Print the result of the view function

handle_after_request called		# after the request is processed
<Response 20 bytes [200 OK]>

handle_teardown_request called
None	# No exception, print the result

127.0. 01. - - [07/May/2021 23:32:25] "The GET/HTTP / 1.1 hello" 200 -
Copy the code


After the visit/index

Then visit with abnormal division by 0 view function, http://127.0.0.1:5000/index

PyCharm prints the result

handle_before_request called

index called	# Print the result of the view function

handle_after_request called
<Response streamed [500 INTERNAL SERVER ERROR]>

handle_teardown_request called
division by zero

[2021- 05-0723:32:40.479] ERROR in app: Exception on /index [GET]
Copy the code


You can see that the before_first_REQUEST request hook is not executed. It only handles the first request of the Flask application, and none of the subsequent requests will be executed.

In the event of an exception, after_Request prints the response of a server error with status code 500. This is a built-in response for Flask.

Teardown_request received an exception and printed the division by zero division by 0 exception.

If Debug mode is on, see if teardown_request only runs in non-debug mode

We can edit the Flask configuration information in PyCharm



I have enabled debug mode and specified the IP address and port as 127.0.0.1:8000

Boot Flask application to visit http://127.0.0.1:8000/index again, page shows as below


If the debugging mode is enabled, the web page displays specific error messages.

Then look at the PyCharm output

handle_before_first_request called

handle_before_request called

index called

127.0. 01. - - [08/May/2021 00:10:13] "GET/index HTTP / 1.1" 500 -
Copy the code


Teardown_request Request hook, not executed, which means it works in non-debug mode.


The source code

The source code has been uploaded to Gitee HuiDBK/FlaskBasic, welcome to visit.

✍ code word is not easy, still hope you heroes support ❤️.


The public,

Create folder X

It took nature tens of billions of years to create our real world, and programmers hundreds of years to create a completely different virtual world. We hammer out bricks with keyboards and build everything with brains. People see 1000 as the authority, we do the opposite and defend 1024. We are not keyboard heroes, we are just extraordinary builders of the ordinary world.