First, the reason
- Application of the object beyond the scope of the application context
- Stack _app_ctx_stack is empty
Second, the solution
act = app.app_context()
act.push()
# Current_app.xxxxx application operation
act.pop()
Note: pycharm breakpoint debugging, current_app may appear LocalProxy: unbound. Mouse over current_app will show the correct content.
Third, in-depth understanding
- Flask context
- The AppContext : encapsulates Flask instance object and other methods and parameters.
- The RequestContext : encapsulates Request objects and other methods and parameters.
- They include Push () , POP () , The __enter __ () , The __exit __ () method.
- Programming process using Flask and Request objects from the context of acquisition.
- Out stack
- A request is received, the package RequestContext , check LocalStack if (application context stack) the stack is empty, if empty, the AppContext push ( Push () ) to the stack (_app_ctx_stack), the then RequestContext push stack (_request_ctx_stack) in. When the request, two elements of the stack would be popped ( POP () ).
- current_app and request are ( LocalProxy ) directed application context stack top element and the request context. It returns Flask instance object app request objects Request .
- Manually stack, the stack
- act = app.app_context () Get AppContext
- act.push () push _app_ctx_stack stack
- act.pop () out of the stack, removing elements
- The stack is generally applied manually to the off-line access applications and unit tests.
Fourth, the context manager
- basic concepts
- Protocol context: implements The __enter __ () and The __exit __ () two methods, i.e., to achieve a protocol context;
- Context Manager: object that implements the context of the agreement.
- The context expression: with the statement, and with must return a context manager.
- __enter__()
- with demo () as d: d values is The __enter __ () method returns the value
- __exit__()
- __exit__ method returns a Boolean value. If with the contents of the code block abnormal, __exit__ returns False , and will throw an exception. Conversely returns True .
- __exit__ method requires pass . 4 parameters, in addition to self other three are exc_type , ext_value , TB . When an exception occurs, exc_type value of the type of anomaly; ext_value is described abnormality; TB is abnormal stack information.
- application
- Links and release of resources.
- Therefore, the manual out of the stack can be written as :
with app.app_context() as atc: #atc.xxxx #xxxx