Flask源码分析之上下文请求流程(请求上下文&应用上下文)

本文详细分析了Flask框架中请求上下文和应用上下文的执行流程,涉及`Flask.__call__`、`RequestContext`、`LocalStack`和`LocalProxy`的使用。通过`app.run()`启动后,`Flask.wsgi_app`调用`request_context`创建`RequestContext`对象,并利用`LocalStack`管理上下文。`LocalStack`的`push`方法将上下文压入栈中,`LocalProxy`用于访问`RequestContext`中的`request`、`session`等属性。文章还探讨了`LocalStack.pop`在请求结束时如何清理上下文。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

from flask import Flask

app = Flask(__name__)


@app.route("/")
def hello():
    return "Hello World"


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

当程序运行时,执行app.run(),会先执行Flask.__call__方法

    def __call__(self, environ, start_response):
        """Shortcut for :attr:`wsgi_app`."""
        return self.wsgi_app(environ, start_response)

call方法中调用Flask.wsgi_app方法

    def wsgi_app(self, environ, start_response):
        ctx = self.request_context(environ)  # 获取environ中的信息,封装在request和session中
        ctx.push()  # 放在Local中的__storage__字典中,字典格式为{"stack":[ctx, ]}  此处stack中存放的为列表形式==栈,详细信息查看文章《Flask多app应用之“栈”详解》
        error = None
        try:
            try:
                response = self.full_dispatch_request()  # 请求
            except Exception as e:
                error = e
                response = self.handle_exception(e)  # 报错
            except:
                error = sys.exc_info()[1]
                raise
            return response(environ, start_response)  # response
        finally:
            if self.should_ignore_error(error):
                error = None
            ctx.auto_pop(error)  # 请求结束,删除__storage__中信息

深入ctx = request_context(environ)

    def request_context(self, environ):
        return RequestContext(self, environ)  # self为Flask对象=app,environ为请求信息

所以此处ctx为RequestContext对象!

接着我们来看RequestContext中都封装了些什么:

深入Request Context(self, environ)

源码可见,RequestContext中封装了我们用到的reqeust,session,so:request = ctx.request , session = ctx.reqeust

class RequestContext(object):
    def __init__(self, app, environ, request=None):
        self.app = app
        if request is None:
            request = app.request_class(environ)
        self.request = request   #  request字段
        self.url_adapter = app.create_url_adapter(self.request)
        self.flashes = None
        self.session = None  # session字段
        self._implicit_app_ctx_stack = []
        self.preserved = False 
        self._preserved_exc = None
        self._after_request_functions = []
        self.match_request(
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值