1. Request hooks

A profile,

Flask’s request hooks refer to functions that are executed before and after a view function is executed, in which we can perform operations. Flask uses the decorator to give us four hook functions.

  • Before_first_request: Executed before the first request is processed. Such as linking database operations
  • Before_request: Executed before each request. Like permission verification
  • After_request: called after each request if no unhandled exceptions are thrown
  • Teardown_request: called after each request, even if an unhandled exception is thrown

Flask’s hooks are similar to the middleware in Django.

Second, the use of

from flask import Flask

app = Flask(__name__)


@app.route('/')
def index(a):
    print('View function execution')
    return 'index page'


Run before the first request.
@app.before_first_request
def before_first_request(a):
    print('before_first_request')


# execute before each request
@app.before_request
def before_request(a):
    print('before_request')


# run after request
@app.after_request
def after_request(response):
    # Response: The response data returned after the previous request is processed, provided that the view function does not fail
    If you need to do additional processing on the response, you can do it here
    Dumps configures the request hook
    # response.headers["Content-Type"] = "application/json"
    print('after_request')
    return response


The view function is called after every request, regardless of whether the view function is abnormal or not, and takes an argument that is an error message from the server
@app.teardown_request
def teardown_request(error):
    print('teardown_request: error %s' % error)


if __name__ == '__main__':
    app.run(debug=True)
Copy the code

We first visit in the browser:

Before_first_request Before_REQUEST View functions perform after_REQUEST TEARdown_REQUEST: errorNone
Copy the code

Let’s refresh the browser and try:

Before_request View functions perform after_REQUEST teardown_REQUEST: errorNone

Copy the code

Welcome to follow my official account: