JSON对象的FastAPI响应模型列表
我正在使用mongodb和fastapi,但无法在没有错误的情况下获得多个文档的响应,这是对我的理解,但无论我阅读什么,我似乎都无法达到底部它?
model.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",
}
}
rutes.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)
有人可以帮忙吗?
I am using MongoDB and FastAPI but can't get my response for more than one document to render without an error, it's a lack of understanding on my part but no matter what I read, I can't seem to get to the bottom of it?
models.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",
}
}
routes.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 data
{
"_id" : ObjectId("62b325f65402e5ceea8a4b6f")
},
"name": "John Smith",
"isActive": true,
"weekPlan": "1234567"
},
{
"_id" : ObjectId("62b325f65402e5ceea9a3d4c"),
"username" : "[email protected]",
"name" : "John Smith",
"isActive" : true,
"weekPlan" : "1234567"
}
This is the error I get:
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)
Can anyone help?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Pymongo的
查找
方法返回光标 - 您必须首先用尽此迭代器,因为Pydantic不知道它应该用光标对象做什么。您可以通过将其作为参数作为
list
的参数来做到这一点:pymongo's
find
method returns a Cursor - you have to exhaust this iterator first, since Pydantic doesn't have any idea what it should do with a Cursor object.You can do this by giving it as an argument to
list
: