Flask context and "working outside application context"

First, the reason

  1. Application of the object beyond the scope of the application context
  2. 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

  1. Flask context
    1. The AppContext : encapsulates Flask instance object and other methods and parameters.
    2. The RequestContext : encapsulates Request objects and other methods and parameters.
    3. They include Push () , POP () , The __enter __ () , The __exit __ () method.
    4. Programming process using Flask and Request objects from the context of acquisition.
  2. Out stack
    1. 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 () ).
    2. 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 .
    3. Manually stack, the stack
      1. act = app.app_context () Get AppContext
      2. act.push () push _app_ctx_stack stack
      3. act.pop () out of the stack, removing elements
      4. The stack is generally applied manually to the off-line access applications and unit tests.

Fourth, the context manager

  1. basic concepts
    1. Protocol context: implements The __enter __ () and The __exit __ () two methods, i.e., to achieve a protocol context;
    2. Context Manager: object that implements the context of the agreement.
    3. The context expression: with the statement, and with must return a context manager.
  2. __enter__()
    1. with demo () as d: d values is The __enter __ () method returns the value
  3. __exit__()
    1. __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 .
    2. __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.
  4. application
    1. Links and release of resources.
    2. Therefore, the manual out of the stack can be written as :
with app.app_context() as atc:
    #atc.xxxx
    #xxxx

 

Guess you like

Origin www.cnblogs.com/blueandsky/p/11628480.html