FastAPI app and request
在 FastAPI 中,Request 对象和 FastAPI 应用实例 (app) 是核心概念,它们在应用状态管理和依赖注入中扮演着关键角色。 本文将介绍它们的关系、设计理念,以及如何利用 app.state 实现单例模式。 FastAPI 对象 FastAPI 对象是整个应用的核心实例: from fastapi import FastAPI app = FastAPI(title="示例应用") 核心职责 路由管理:通过 @app.get()、@app.post() 等装饰器定义 URL 到视图函数的映射。 中间件和事件管理:可注册中间件处理请求/响应,支持 startup 与 shutdown 事件。 应用状态管理:提供 app.state,可存放全局单例对象、数据库连接池、配置等。 异常处理与依赖注入:管理异常处理器,并协助依赖注入机制。 单例模式存储 这里要使用 app 的 State 对象存储单例,app 中定义如下 # app self.state: Annotated[ State, Doc( """ A state object for the application. This is the same object for the entire application, it doesn't change from request to request. You normally wouldn't use this in FastAPI, for most of the cases you would instead use FastAPI dependencies. This is simply inherited from Starlette. Read more about it in the [Starlette docs for Applications](https://www.starlette.dev/applications/#storing-state-on-the-app-instance). """ ), ] = State() State 源码如下,简单看就是一个字典 ...