简体   繁体   English

如何通过 FastAPI 和 Pydantic 放置对象列表

[英]How to Put list of object by FastAPI and Pydantic

I am trying to learn FastAPI and Pydantic to put a list of object into MongoDB, but I got an error saying 422 Unprocessable Entity .我正在尝试学习 FastAPI 和 Pydantic 以将对象list放入 MongoDB,但我收到一条错误消息422 Unprocessable Entity I understand the error message indicated the server understands the JSON format, but is unable to handle it.我理解错误消息表明服务器理解 JSON 格式,但无法处理它。 I tried to wrap it with another model, but it looks like it doesn't work.我试着用另一个模型包裹它,但它看起来不起作用。

Let's say I have a list of object as:假设我有一个对象列表:

[
  {
    "date": "2022-12-13",
    "symbol": "nsht",
    "price": "45.12"
  },
  {
    "date": "2022-12-13",
    "symbol": "asdf",
    "price": "45.14442"
  }
]

And I want to add it to the database by following object model as:我想通过以下对象模型将其添加到数据库中:

class EODCoinModel(BaseModel):
    id: PyObjectId = Field(default_factory=PyObjectId, alias="_id")
    date: str = Field(...)
    symbol: str = Field(...)
    price: float = Field(...)
  
    class Config:
        allow_population_by_field_name = True
        arbitrary_types_allowed = True
        json_encoders = {ObjectId: str}
        schema_extra = {
            "example": {
                "date": "2022-12-13",
                "symbol": "AAPL",
                "price": "45.12"
            }
        }

class ItemList(BaseModel):
    data: List[EODCoinModel]

And PUT method as: PUT 方法为:

@app.post("/", response_description="Add new coin", response_model=ItemList)
async def create_coin(coin: ItemList = Body(...)):
    coin = jsonable_encoder(coin)
    print(coin)
    new_coin = await db["coin"].insert_one(coin)
    created_coin = await db["coin"].find_one({"_id": new_coin.inserted_id})
    return JSONResponse(status_code=status.HTTP_201_CREATED, content=created_coin)

在此处输入图像描述

the Post request expects a body like this: Post 请求需要这样的正文:

    {"data" : [
      "date": "2022-12-13",
      "symbol": "nsht",
      "price": "45.12"]
    }

So then I ended up with not using Pydantic model validation.所以我最终没有使用 Pydantic 模型验证。 Just take the whole list and do inset_many.只需获取整个列表并执行 inset_many。

@app.post("/", response_description="Add new coin")
async def create_coin(coin: List):
    coin = jsonable_encoder(coin)
    print(coin)
    new_ coin = await db["coin"].insert_many(coin)
    return JSONResponse(status_code=status.HTTP_201_CREATED)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM