且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将来的任务附加到另一个循环

更新时间:2023-01-08 15:11:19

您可以在全局范围内使用 mongodb motor 客户端,但是创建和关闭它应该在异步函数中完成.在应用程序的 startup shutdown 处理程序中执行此操作的***方法.像这样:

You can have mongodb motor client in the global scope, but creating and closing it should be done inside an async function. The most preferable way of doing that in startup and shutdown handler of the application. Like so:

# mongodb.py
from motor.motor_asyncio import AsyncIOMotorClient


db_client: AsyncIOMotorClient = None


async def get_db_client() -> AsyncIOMotorClient:
    """Return database client instance."""
    return db_client


async def connect_db():
    """Create database connection."""
    db_client = AsyncIOMotorClient(DB_URL)

async def close_mongo_connection():
    """Close database connection."""
    db_client.close()

# main.py
app = FastAPI(title=PROJECT_NAME)
...
app.add_event_handler("startup", connect_db)
app.add_event_handler("shutdown", close_db)