In flask applications, all flask applications must create an application instance. The Web server passes the request it receives from the client through the WSGI protocol to the object for processing. At this point, it provides a magical environment called context, which allows some objects to be globally visible, so that your view functions can access these objects to do some processing, while at the same time there are so many requests to ensure thread safety.
There are two contexts in flask, the application context and the request context, in which 4 variables are exposed:
Application context
|
Current_app |
Application instances for active applications |
Application context |
G |
Temporarily stores data while processing requests, and each request is reset |
Request context |
Request |
Request object that encapsulates the contents of the HTTP request sent by the client |
Request context |
Session |
The dictionary used to store values, which are remembered in the request |
Flask will push both contexts before scheduling each request, and the request is processed and removed. When the application context is push, its corresponding two variables can be accessed by the thread, and the request context is the same. Of course, if these contexts are not activated, accessing these variables will cause an error.
As an example:
>>>from flask Import flask, Current_app>>>app = Flask (__name__) >>>current_apptraceback ( Most recent call last): ... Runtimeerror:working outside of application Context>>>app_ctx = App.app_context () >>>app_ctx.push () >>>current_app.name ' __main__ ' >>>app_ctx.pop ()
Flask Web Development Reading notes