237.13.flask-上下文管理

1.上下文管理流程

  • 流程图
# coding=utf8
"""
threading.local
上下文管理
"""
from flask import Flask, request, session

app = Flask(__name__)
app.__call__

@app.route("/index")
def index():
    request.method
    pass


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

"""
1.用户请求一旦到来执行app.__call__方法
2.__call__方法
    1.self.wsgi_app(environ, start_response)
    2.ctx = self.request_context(environ)  # 初始化request和session以及完成路由匹配
    3.ctx.push() - >_request_ctx_stack.push(self)  # 使用一个类似于threading.local容器存放ctx对象
    4.给session赋值
    5.response = self.full_dispatch_request()  # 找试图函数
    6.preprocess_request  # 执行before_request装饰器
    7.rv = self.dispatch_request() # 找试图函数执行代码
    N.self.finalize_request(rv) # 执行after_request, 将session设置进到cookie
    N+1.ctx.auto_pop(error) # 删除上线文
3.在试图函数中获取request.method以及session[key]="123", session[key1]是如何进行的?
    1.request.method
        request = LocalProxy(partial(_lookup_req_object, 'request'))
        LocalProxy初始化了一个object.__setattr__(self, "_LocalProxy__local", local) == self.__local=local _LocalProxy__表示他是私有方法
        request.method 执行LocalProxy的 __getattr__方法, 执行getattr(self._get_current_object(), name) name="method"
        self._get_current_object() == self.__local() == _lookup_req_object('request') == ctx.request
        此时getattr(ctx.request, "method") == request.method
    2.session[key]="123" 以及 session[key1]与request是完全一样的
        LocalProxy(partial(_lookup_req_object, 'session')) 经过request的流程我们发现其实他就是去ctx中取session对象
        session[key]="123" 执行__setitem__方法 self._get_current_object()[key] = value
        其中self._get_current_object()就是我们的session对象他是一个字典, 设置值
        session[key1]执行__getitem__方法, getattr(self._get_current_object(), name) = session.get("key1")

4.flask中创建了几个LocalStack与local对象?
    都是两个, 一个LocalStack创建一个local对象
5.flask中的g对象,范围是什么?
    AppContext: 请求刚进来的时候创建了, 请求结束时销毁了
    g 可以当做session使用么? 不可以, 以为每个请求来时创建, 请求结束时销毁了, 但是没有从cookie中取值放入g中因此它是一次性的
"""

2.全局插入变量

# coding=utf-8
from flask import Flask, g

app = Flask(__name__)
app.config.from_object("settings.DevelopmentConfig")


@app.before_request
def bf():
    g.x = 666  # 但是可以在请求进入试图函数之前设置进去, 每个试图函数都可以拿到


@app.route("/index1", methods=["POST", "GET"])
def index1():
    g.x = 1
    pass


@app.route("/index2", methods=["POST", "GET"])
def index2():
    print(g.x)  # 获取不到x, 因此g每个请求都是新的
    return "index"


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

``
posted @ 2022-06-02 14:11  楠海  阅读(27)  评论(0编辑  收藏  举报