Summary of knowledge related to Python Flask request extension and middleware

  • 2021-11-10 09:56:57
  • OfStack

1. Request extension

1.before_request

Function: Analogous to process_request in django middleware, it executes before the request arrives to execute the routing function. However, if there are multiple sequences, it is executed from top to bottom.

Application: User login authentication based on it

Note: If the return value of before_request is not the empty value of None, but other values are returned, then the subsequent requests will not be executed, and this request will be returned directly. If after_request is defined, it will be executed next, and finally the response of this request will end.


@app.before_request
def process_request(*args,**kwargs):
    if request.path == '/login':
        return None
    user = session.get('user_info')
    if user:
        return None
    return redirect('/login') 

2.after_request

Function: Analogous to process_response in django middleware, if the request does not have an exception, it will be executed before the request returns to return. However, if there are multiple sequences, it will be executed from bottom to top.


@app.after_request  #  Post-execution 
def process_response1(response):
    print('process_response1  Go away ')
    return response

@app.after_request  #  Execute first 
def process_response2(response):
    print('process_response2  Go away ')
    return response

3.before_first_request

Function: Execute when the project starts and receives the first request.

Application: Project initialization is used to ensure that the project will not continue to execute as long as it is not restarted in the future.


@app.before_first_request
def first():
    print(' My first 1 Times ')

4. teardown_request

Function: After every 1 routing function is executed, even if it encounters an exception, it will be executed. (Hint: Returning reutrn has no effect and cannot control the returned result)

Application: Logging


@app.teardown_request  
def ter(e):  # e Is to go up 1 Exception information captured during the execution of routing correspondence .
    print(e)
    print(' I am teardown_request ')

5.errorhandler

What you do: Bind the error status code to catch the server error and return the corresponding error page.


@app.errorhandler(500)
def error_500(arg):
    return render_template('error.html', message='500 Errors ')


@app.errorhandler(404)
def error_404(arg):
    return render_template('error.html', message='404 Errors ')

6.template_global

Function: Global label, in any html page can be used directly, do not need to pass parameters in render_template before use.


@app.template_global()
def sb(a1, a2):
    return a1 + a2

# html Use directly in the page ,  No need to pass parameters .
{{ sb(1,2) }}

7.template_filter


@app.template_filter()
def db(a1, a2, a3):
    return a1 + a2 + a3

# html Use directly in the page ,  No need to pass parameters .  Among them 1 Pass to a1, 2 Pass to a2, 3 Pass to a3. ( Prompt : Django Filters in can only be passed at most 2 Parameters )
{{ 1|db(2,3) }}

Summary:

1. Focus on mastering before_request And after_request

2. Note that there are multiple situations and the execution sequence

3. before_request After the request is intercepted (that is, there is an return value), response Execute everything

2. Middleware


class Md(object):
    def __init__(self, old_wsgi_app):
        self.old_wsgi_app = old_wsgi_app

    def __call__(self, environ, start_response):
        print(' Before beginning ')
        ret = self.old_wsgi_app(environ, start_response)
        print(' After the end ')
        return ret


if __name__ == '__main__':
    # 1.  We found that when executing app.run Method, finally execute the run_simple , final execution app(), That is, it is executing app.__call__ Method 
    # 2.  In __call__ Inside, the execution is self.wsgi_app(). Then we hope to implement his own wsgi Do something before. 
    # 3.  So let's use it first Md Class __init__ Save the previous wsgi, Then we use the app.wsgi Convert into Md Object of. 
    # 4.  Then execute the new one app.wsgi_app Is to execute Md Adj. __call__ Method. 
    # 5.  Finally, put the original wsgi_app Replace with custom 

    app.wsgi_app = Md(app.wsgi_app)
    app.run()

Related articles: