首页 > 解决方案 > 我调试 Fastapi + mongdb 时出错

问题描述

我在这段代码中有 2 个版本来解释我的问题。当我执行uvicorn main:app --reload两个版本都可以正常工作。调试时出现我的问题。

当我使用版本 1 并评论版本 2 时,我可以毫无问题地进行调试,但是当我使用版本 2 并评论版本 1 时,我收到此错误:

created_user = 等待 users_collection.insert_one(form_dict)

RuntimeError: Task <Task pending name='Task-7' coro=<RequestResponseCycle.run_asgi() 在 C:\Users\c\PycharmProjects\fastapi_test_fallo_loop\lib\site-packages\uvicorn\protocols\http\h11_impl.py 运行: 394> cb=[set.discard()]> 在 C:\Users\c\AppData\Local\Programs\Python\Python38-32\lib\asyncio\ 获得未来 <Future pending cb=[_chain_future.._call_check_cancel() futures.py:360]> 附加到不同的循环

为什么会出现这个错误?

我应该始终使用版本 1 吗?

from motor.motor_asyncio import AsyncIOMotorClient

# version 1
'''
class DataBase:
   client: AsyncIOMotorClient = None
   usersDB = None

db = DataBase()

async def connect_to_mongo():
   db.client = AsyncIOMotorClient("mongodb://mongo:mongo@19*****:27017/admin?retryWrites=false")
   db.usersDB = db.client.app

async def close_mongo_connection():
   db.client.close()

# end version 1
'''
# version 2
DB_CLIENT = AsyncIOMotorClient("mongodb://mongo:mongo@19*****:27017/admin?retryWrites=false")
db = DB_CLIENT['app']
# end version 2

在这里,我的 main.py 有一个注册用户并解释我的问题的方法

from fastapi import FastAPI, Form, HTTPException
# from app.mongodb import connect_to_mongo, close_mongo_connection  # version 1
from app.mongodb import db  # version 2, version 1
from fastapi.responses import JSONResponse

app = FastAPI()


# app.add_event_handler("startup", connect_to_mongo)  # version 1
# app.add_event_handler("shutdown", close_mongo_connection)  # version 1


@app.post("/register")
async def register(username: str = Form(..., max_length=50)):
   form_dict = {'username': username}
   # users_collection = db.usersDB.get_collection('users')  # version 1
   users_collection = db.get_collection('users')  # version 2
   created_user = await users_collection.insert_one(form_dict)
   if created_user:
      return JSONResponse(status_code=200,
                        content='user is created correctly')
   else:
      raise HTTPException(status_code=400,
                        detail='user is not created correctly')


   if __name__ == "__main__":
     import uvicorn
     uvicorn.run(app, host="127.0.0.1", port=8000)

标签: pythonmongodbfastapiuvicorn

解决方案


推荐阅读