【问题标题】:How to pass the path parameter to the Pydantic model?如何将路径参数传递给 Pydantic 模型?
【发布时间】:2021-12-23 04:01:31
【问题描述】:

有没有办法做到以下几点?

from typing import Optional
from fastapi import FastAPI
from pydantic import BaseModel


class Item(BaseModel):
    id: str
    name: str
    description: Optional[str] = None
    price: float
    tax: Optional[float] = None


app = FastAPI()


@app.post("/items/{item_id}")
async def create_item(item: Item):
    return item

我想在Item 模型中包含item_id 路径参数值。

有可能吗?

【问题讨论】:

    标签: python fastapi


    【解决方案1】:

    FastAPI 中的 Pydantic 用于定义数据模型。你可以这样做:

    from typing import Optional
    from fastapi import FastAPI
    from pydantic import BaseModel
    
    
    class Item(BaseModel):
        id: Optional[str] = None
        name: str
        description: Optional[str] = None
        price: float
        tax: Optional[float] = None
    
    
    app = FastAPI()
    
    
    @app.post("/items/{item_id}")
    async def create_item(item_id, item: Item):
        item.id = item_id
        return item
    

    请注意,id 被声明为可选,以避免请求中的正文参数出现验证问题。实际上,您不会在正文中传递id,而是在路径中传递。

    如有必要,您还可以将请求模型与响应模型解耦(请参阅here)。这取决于你需要什么。

    【讨论】:

      【解决方案2】:
      1. 将您的id: str 替换为id: Optional [str] = None

      2. 将您的 create_item (item: Item) 替换为 create_item (item_id, item: Item):

      3. 在您的async 下添加item.id = item_id。显然然后你离开了 ruo return item

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-10-12
        • 2021-12-02
        • 2018-12-26
        • 1970-01-01
        • 1970-01-01
        • 2016-06-17
        相关资源
        最近更新 更多