上下文管理
-
threading.local
-
请求上下文:RequstContext
- request
- session
-
应用上下文:AppContext
- app(current_app)
- g
1.请求到来
# 1.请求封装
# 1.1.将请求相关的数据environ封装到了RequestContext对象中
# 1.2.再讲对象封装到local中(每个线程/每个协程独立空间存储)
# ctx.app # 当前APP的名称
# ctx.request # Request对象(封装请求相关东西)
# ctx.session # 空
_request_ctx_stack.local = {
唯一标识:{
"stack":[ctx, ]
},
唯一标识:{
"stack":[ctx, ]
},
}
# 2.应用封装
# 2.1 app_ctx = AppContext对象
# 2.2 app_ctx = AppContext对象
# app_ctx.app
# app_ctx.g
_app_ctx_stack.local = {
唯一标识:{
"stack":[app_ctx, ]
},
唯一标识:{
"stack":[app_ctx, ]
},
}
2.应用
from flask import request,session,g,current_app
print(request,session,g,current_app)
都会执行相应LocalProxy对象的 __str__
current_app = LocalProxy(_find_app)
request = LocalProxy(partial(_lookup_req_object, 'request'))
session = LocalProxy(partial(_lookup_req_object, 'session'))
current_app = LocalProxy(_find_app)
g = LocalProxy(partial(_lookup_app_object, 'g'))
flask.g
生命周期是一个请求,可以用来存放自定义数据,不要使用request对象存储数据,因为里面有太多的数据,可能会被覆盖.