from contextlib import asynccontextmanager @asynccontextmanager async def managed_transaction(db: AsyncSession): try: yield await db.commit() except Exception: await db.rollback() raise # 在路由中使用 async def create
app = FastAPI()# Redis 连接池配置REDIS_URL ="redis://192.168.252.128:6379/0"@asynccontextmanagerasyncdeflifespan(app: FastAPI):# 初始化 Redis 客户端app.state.redis =awaitaioredis.from_url(REDIS_URL)yield# 关闭 Redis 连接awaitapp.state.redis.close() app.router.lifespan_context = lifespande...
# 对应历史版本格式是#@app.on_event("startup")#async def startup_event():# log.info("app start")##@app.on_event("shutdown")#async def shutdown_event():# log.info("app shutdown")@asynccontextmanagerasyncdeflifespan(app:FastAPI): log.info("app start")yieldlog.info("app shutdown"...
示例Python实现代码:# -*- coding: utf-8 -*-fromcontextlibimportasynccontextmanagerfromfastapiimport...
@asynccontextmanager async def lifespan(app: FastAPI): # Load the ML model ml_models["answer_to_everything"] = fake_answer_to_everything_ml_model yield # Clean up the ML models and release resources ml_models.clear() app = FastAPI(lifespan=lifespan) ...
async def destory(request: Request): await request.state.engine.close() 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 应用启动和关闭事件(新版本) 新版本推荐使用lifespan+异步上下文 from contextlib import asynccontextmanager app = FastAPI() ...
fromcontextlibimportasynccontextmanagerfromfastapiimportFastAPI,Depends,HTTPExceptionfromsqlalchemy.ext.asyncioimportAsyncSessionfromsqlalchemyimportselectfrom.databaseimportget_async_db,User,initialize_database@asynccontextmanagerasync def lifespan(app: FastAPI):# 启动:初始化数据库await initialize_database()yield...
# app.py 中的代码 import asyncio from contextlib import asynccontextmanager from fastapi import FastAPI from config.config import settings # 配置 from src.api.v1.services.kafka.kafka import kafka_consumer # kafka消费者 from src.route.router import router # 路由 @asynccontextmanager async def lif...
)@asynccontextmanagerasyncdeflifespan(app: FastAPI) -> AsyncGenerator[None,None]:# Register a websocket adapter to `FastAPI`app.add_api_websocket_route("/onebot/v11/ws", FastBot.ws_adapter)awaitasyncio.gather( *( init()ifasyncio.iscoroutinefunction(init)elseasyncio.to_thread(init)forpluginin...
简介:FastAPI(35)- 依赖项中使用 yield + Context Manager 上下文管理器 什么是 Context Manager 上下文管理器 在Python 中,是可以在 with 语句中使用的任何 Python 对象,比如通过 with 来读取文件 with open("./somefile.txt") as f: contents =f.read() ...