10.Flask context

10.Flask context

1.1.local thread isolation object

When local objects are not used

from threading import Thread

request = '123'

class MyThread(Thread):
    def run(self):
        global request
        request ='abc'
        print('sub-thread',request) #sub-thread abc

mythread = MyThread()
mythread.start()
mythread.join()

print('Main thread',request) #Main thread abc

If you use local objects, they are isolated in each thread

from threading import Thread
from werkzeug.local import Local

locals = Local()
locals.request = '123'

class MyThread(Thread):
    def run(self):
        locals.request ='abc'
        print('sub-thread',locals.request) #sub-thread abc

mythread = MyThread()
mythread.start()
mythread.join()

print('Main thread',locals.request) #Main thread 123

1.2.app context and request context

 Application context and request context are stored in a'LocalStack' stack, and operations related to the application app must use the application context, such as obtaining the name of the current app through current_app. Request-related operations must use the request context, such as using url_for to reverse the view function.

  • In the view function, there is no need to worry about the context, because the view function is to be executed, the name must be executed by accessing the URL. In this case, the bottom layer of Flask has automatically helped us request the previous year's text and application context. Are pushed into the corresponding stack.
  • If you want to perform related operations outside the view function, the name must be manually pushed into the related context
  • Manually push the request context: When pushing the request context to the stack, it will first determine whether there is an application context. If not, it will first push the application context to the stack, and then push the request context to the stack.

app context

from flask import Flask,current_app

app = Flask(__name__)

#If you access outside the view function, you must manually push an app context to the app context stack
#the first method
# app_context = app.app_context()
# app_context.push()
# print(current_app.name)

#The second method
with app.app_context():
    print(current_app.name) #context_demo

@app.route('/')
def index():
    # You can directly access current_app.name inside the view function
    print(current_app.name) #context_demo
    return'Hello World!'

if __name__ =='__main__':
    app.run(debug=True)

Request context

from flask import Flask,current_app,url_for

app = Flask(__name__)

#Application context
#If you access outside the view function, you must manually push an app context to the app context stack
with app.app_context():
    print(current_app.name) #context_demo

@app.route('/')
def index():
    # You can directly access current_app.name inside the view function
    print(current_app.name) #context_demo
    return'Hello World!'

@app.route('/list/')
def my_list():
    return'my_list'

# Request context
with app.test_request_context():
    # Manually push a request context into the request context stack
    # If there is no application context in the current application context stack
    # Then it will first push an application context to the stack
    print(url_for('my_list'))

if __name__ =='__main__':
    app.run(debug=True)

Why does the context need to be placed on the stack?

1. Application context:

The bottom layer of Flask is based on werkzeug, werkzeug can contain multiple apps, so use a stack to save at this time, if you are using app1, then app1 should be at the top of the stack, if you run out of app1, then app should be from the stack Delete, so that other codes can use the following app.

2. Application context:

If we are writing test code or offline scripts, we may sometimes need to create multiple request contexts. At this time, we need to store them in a stack. When using which request context, put the corresponding request context on the top of the stack, and remove the request context from the stack when it is used up.

1.3. Thread-isolated g object

The g object is available during the entire Flask application running, and it is also thread-isolated like the request. This object is specially used to store some data customized by the developer, so that it can be used in the entire Flask program. The general usage is to bind some frequently used data to it, and then it will be taken directly from g in the future, instead of passing parameters, which is more convenient.

Reference: https://cloud.tencent.com/developer/article/1172860 10. Flask Context-Cloud + Community-Tencent Cloud