我正在使用 MongoDB 和 FastAPI,但無法獲得對多個檔案的回應而不會出現錯誤,這是我缺乏理解,但無論我閱讀什么,我似乎都無法深入了解它?
模型.py
from pydantic import BaseModel, constr, Field
#Class for a user
class User(BaseModel):
username: constr(to_lower=True)
_id: str = Field(..., alias='id')
name: str
isActive : bool
weekPlan : str
#Example to provide on FastAPI Docs
class Config:
allow_population_by_field_name = True
orm_mode = True
schema_extra = {
"example": {
"name": "John Smith",
"username": "[email protected]",
"isActive": "true",
"weekPlan": "1234567",
}
}
路線.py
from fastapi import APIRouter, HTTPException, status, Response
from models.user import User
from config.db import dbusers
user = APIRouter()
@user.get('/users', tags=["users"], response_model=list[User])
async def find_all_users(response: Response):
# Content-Range needed for react-admin
response.headers['Content-Range'] = '4'
response.headers['Access-Control-Expose-Headers'] = 'content-range'
users = (dbusers.find())
return users
mongodb json資料
{
"_id" : ObjectId("62b325f65402e5ceea8a4b6f")
},
"name": "John Smith",
"isActive": true,
"weekPlan": "1234567"
},
{
"_id" : ObjectId("62b325f65402e5ceea9a3d4c"),
"username" : "[email protected]",
"name" : "John Smith",
"isActive" : true,
"weekPlan" : "1234567"
}
這是我得到的錯誤:
await self.app(scope, receive, send)
File "C:\Git2\thrive-app-react\backend\venv\lib\site-packages\starlette\routing.py", line 670, in __call__
await route.handle(scope, receive, send)
File "C:\Git2\thrive-app-react\backend\venv\lib\site-packages\starlette\routing.py", line 266, in handle
await self.app(scope, receive, send)
File "C:\Git2\thrive-app-react\backend\venv\lib\site-packages\starlette\routing.py", line 65, in app
response = await func(request)
File "C:\Git2\thrive-app-react\backend\venv\lib\site-packages\fastapi\routing.py", line 235, in app
response_data = await serialize_response(
File "C:\Git2\thrive-app-react\backend\venv\lib\site-packages\fastapi\routing.py", line 138, in serialize_response
raise ValidationError(errors, field.type_)
pydantic.error_wrappers.ValidationError: 1 validation error for User
response
value is not a valid list (type=type_error.list)
任何人都可以幫忙嗎?
uj5u.com熱心網友回復:
pymongo 的find方法回傳一個 Cursor - 你必須先用盡這個迭代器,因為 Pydantic 不知道它應該如何處理 Cursor 物件。
您可以通過將其作為引數來做到這一點list:
@user.get('/users', tags=["users"], response_model=List[User])
async def find_all_users(response: Response):
...
return list(dbusers.find())
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/495016.html
