python - 我调试 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)
解决方案
推荐阅读
- javascript - 从 JavaScript 中的 API URL 获取信息或做出反应
- javascript - 获取插入符号/光标的位置场地
- r - %in%/match 和由数值确定的逻辑索引的奇怪行为
- php - 连接到一个数据库但使用 PHP 和 Firebird 查询另一个数据库
- apache-spark - Spark 用引号内的引号写入 CSV
- dataframe - 我如何在 dict 中只选择主题
- flutter - 自从将 Flutter 从 1.26.0-8.0.pre 更新到 2.2.1 后,Flutter 桌面应用程序在全屏时出现滞后
- rust - rust doc 注释中的额外空格被解释为 doc test
- c# - 我想在列表中添加一个新对象。有人可以解释如何做到这一点吗?
- python - 如何从我的时间戳列中分离 pandas 中的数据