This is the 17th day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021.

Context concept

Context, to put it bluntly, is the so-called context, which is the language environment. For example, we may not understand the meaning of a single sentence in an article, but we can easily understand it through the language environment in which the sentence is located and the sentences before and after it.

We can think of a context as a snapshot of the current environment, an object that holds state. At some point in the code execution, depending on the code logic of the context, you can determine the environment variables to be used at the current time, etc.

Flask context

Flask has two types of context: Application context and Request context:

  • Application: Refers to the Flask object created by calling app = Flask(__name__)

  • Request: Refers to the Request objects created inside the Flask objects each time an HTTP request occurs

Request context

In Flask, when the request is processed, the application will generate the “request context” object, which stores the relevant data information of the current request. The whole request processing process will be carried out in this context object, ensuring that the request processing process is independent from interference.

Request context objects include Request and session. The following uses Request as an example.

In Flask’s starter series, request hooks! In Flask we said that there are four common request hooks: before_first_REQUEST, before_request, after_request, and teardown_request.

@app.before_first_request
def before_first_request() :
    print(request.url)
    print('before_first_request')


@app.before_request
def before_request() :
    print(request.url)
    print('before_request')


@app.after_request
def after_request(response) :
    print(request.url)
    print('after_request')
    return response


@app.teardown_request
def teardown_request(e) :
    print(request.url)
    print('teardown_request')


@app.route('/test')
def test() :
    print(request.url)
    return 'test'
Copy the code

Through the request we find that we have direct access to the Request object in each of the request hook decorator handlers. Furthermore, the inability to access the Request object in other ordinary functions means that the Request object is not really a global variable, but is accessible for the lifetime of the request context, and not outside of the lifetime of the request. The above request hook decorates the handler, which executes at different stages of the request processing, and naturally has access to the Request object internally.

Application context

The request context is related to the request, and the request context object stores the relevant data information of the request. The application context is related to the current application, and the application context object contains the information related to the current application.

The application context objects are: current_APP and G.

We learned that each request has a request object corresponding to the view function, which can be understood as the current request. The program also has multiple instances. In order to obtain the corresponding program instance instead of a fixed one, We need to use the current_APP variable.

from flask import Flask, current_app

app = Flask("tigeriaf_app")


@app.route('/')
def index() :
    return 'Hello, {}! '.format(current_app.name)
Copy the code

Current_app is a local agent, it is of type werkzeug. Local. LocalProxy, its agent is app object, that is to say current_app = = LocalProxy (app). So current_app.name is used to get the name of the current application, which is tigeriaf_app. Current_app is used because it is also a ThreadLocal variable, and changes to it won’t affect other threads. We can get the APP object with the current_app._get_current_object() method. You can also store custom variables in current_APP.

Current_app exists only in the requesting thread, and its lifetime is in the application context. Current_app is also unavailable without application context.

The G object is a temporary variable in the Flask program global and acts as an intermediary. We can pass some data through it. G holds the global variable of the current request, which will be reset with each request. We usually use it together with the request hook to hold the global variable needed before each request processing, such as the user object currently logged in, database connection, etc. For example, if a g object is used to hold the token of a request, the corresponding value can be obtained directly using the g.name in the view function.

from flask import g

@app.before_request
def get_token() :
    g.name = request.headers.get("token")
Copy the code

Original is not easy, if small partners feel helpful, please click a “like” and then go ~

Finally, thank my girlfriend for her tolerance, understanding and support in work and life!