gpt4 book ai didi

python - 附加到不同循环的 future 任务

转载 作者:行者123 更新时间:2023-12-03 16:47:07 28 4
gpt4 key购买 nike

我正在尝试在 FastAPI 中连接到 mongodb。我反复收到此异常。
文件 - main.py

app = FastAPI(
title=config.PROJECT_NAME, docs_url="/api/docs", openapi_url="/api"
)

@app.get("/api/testing")
async def testit():
user_collection = readernetwork_db.get_collection("user_collection")
all_users = await user_collection.find_one({"email": "sample_email"})
print("all users --- ", all_users)
return all_users

if __name__ == "__main__":
uvicorn.run("main:app", host="0.0.0.0", reload=True, port=8888)
文件 - session.py
import motor.motor_asyncio
from app.core import config


print("here we go again....")
client = motor.motor_asyncio.AsyncIOMotorClient(
config.MONGOATLAS_DATABASE_URI)
readernetwork_db = client.get_database("readernetwork")
异常(exception) -:
all_users = await user_collection.find_one({"email": "sample_email"})

RuntimeError: Task <Task pending name='Task-4' coro=<RequestResponseCycle.run_asgi() running at /usr/local/lib/python3.8/site-packages/uvicorn/protocols/http/h11_impl.py:389> cb=[set.discard()]> got Future <Future pending cb=[_chain_future.<locals>._call_check_cancel() at /usr/local/lib/python3.8/asyncio/futures.py:360]> attached to a different loop
我不知道我哪里出错了。我应该为电机指定一个事件循环吗?

最佳答案

您可以在全局范围内拥有 mongodb motor 客户端,但应在异步函数内创建和关闭它。在应用程序的 startupshutdown 处理程序中执行此操作的最佳方法。像这样:

# 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_db():
"""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)

关于python - 附加到不同循环的 future 任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65542103/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com