JSON对象的FastAPI响应模型列表

发布于 2025-02-10 04:16:03 字数 2854 浏览 0 评论 0原文

我正在使用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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

忆悲凉 2025-02-17 04:16:03

Pymongo的查找方法返回光标 - 您必须首先用尽此迭代器,因为Pydantic不知道它应该用光标对象做什么。

您可以通过将其作为参数作为list的参数来做到这一点:

@user.get('/users', tags=["users"], response_model=List[User])
async def find_all_users(response: Response):
    ...
    return list(dbusers.find())

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:

@user.get('/users', tags=["users"], response_model=List[User])
async def find_all_users(response: Response):
    ...
    return list(dbusers.find())
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文