11. Flask hook function

11. Flask hook function

     A hook function in Flask is a function that uses a specific decorator. Why is it called a hook function? Because a hook function can insert a piece of code that you want to execute in the normally executed code, then this kind of function is called a hook function.

  • before_first_request: The hook function that will be executed after the Flask project is deployed for the first time.
  • before_request: The request has reached Flask, but it is called before entering the specific view function. Generally, this is before the function, we can process some data that will be used later to facilitate the use of the view function.

before_request

@app.before_first_request
def first_request():
    print('Only executed before processing the first request')

@app.before_request
def before_request():
    print('Execute before the execution of the view function')

context_rocessor

 Only with this hook function, a dictionary must be returned. The value of this dictionary can be used in all templates. The function of this hook function is that if some variables are used in many templates, then you can use this hook function to return instead of writing in the render_template summarized by each view function, which can make the code more concise And well maintained.

@app.context_processor
def context_rocessor():
    return {{'current_user':'xxx'}}

 errorhandler

When an exception occurs, such as 404, 500 errors, custom error pages, under the hook function decorated by errorhangdler:

  • To return the status code
  • Must write a parameter to accept the wrong information

Use flask.abort to throw corresponding errors manually, for example, developers can manually throw a 404 error when they find that the parameters are incorrect.

@app.errorhandler(500)
def server_error(error):
    return render_template('500.html'),500

@app.errorhandler(404)
def page_not_found(error):
    return render_template('404.html'),404
Reference: https://cloud.tencent.com/developer/article/1172861 11. Flask hook function-Cloud + Community-Tencent Cloud