简体   繁体   English

Python / pydantic / FastAPI - 将此数据结构描述为模式模型?

[英]Python / pydantic / FastAPI - describe this datastructure as a Schema Model?

Problem问题

I have a data structure of nested lists of Dicts that I am trying to build a response_model for in FastAPI using Pydantic models but it's proving so far impossible.我有一个嵌套的字典列表的数据结构,我正在尝试使用 Pydantic 模型在 FastAPI 中为它构建一个response_model ,但到目前为止证明是不可能的。 As soon as I apply the response_model= directive the data returns empty from the API.一旦我应用response_model=指令,数据就会从 API 返回空。 If I remove the response_model= directive the same query to the API results in data returning just fine and has content.如果我删除response_model=指令,对 API 的相同查询会导致数据返回得很好并且有内容。

The Data looks like the following:数据如下所示:

[
    {
        'code': 'trabant',
        'description': 'East German Trabant',
        'listings': [
            {
                 id: 1000,
                 cat_no: "Trabi1",
                 descript: "Trabant Interior Mirror"
                 price: Decimal(16.95),
                 veh: 'trabant',
                 sec: 'interior'
             },
             {
                 id: 1001
                 cat_no: "Trabi2",
                 descript: "Trabant Interior Clock"
                 price: Decimal(56.95),
                 veh: 'trabant',
                 sec: 'interior'
             }
         ]
    },
    {
        'code': 'skoda',
        'description': 'Czech Skoda',
        'listings': [
            {
                  id: 2001,
                  cat_no: "Skoda5",
                  descript: "Front Grille",
                  price: Decimal(36.95),
                  veh: 'skoda',
                  sec: 'bodywork'
             },
             {
                  id: 2002
                  cat_no: "Skoda6",
                  descript: "Skoda Grille Badge - Front"
                  price: Decimal(16.95),
                  veh: 'skoda',
                  sec: 'bodywork'
             }
        ]
    }
]

Which when boiled down to it's structure looks like:当归结为它的结构时,它看起来像:

] # root list
    { #can be any vehicle in a list of 40+
        'code': #vehicle's db code
        'description': #vehicle's textual name>,
        'listings': [ #list of catalogue items for this vehicle
            {
                id: #db id,
                cat_no: #Customer SKU,
                descript: #Description of a part,
                price: #Decimal value for price, no evil floats here!,
                veh: #db code for vehicle,
                sec: #db code for section
            }
        ]
    }
]

I tried to describe it using these Pydantic models:我试图用这些 Pydantic 模型来描述它:

class ORMBaseModel(BaseModel):
    class Config:
        orm_mode = True

class CatListing(ORMBaseModel):
    id: int
    cat_no: str
    descript: str
    sec: str
    veh: str
    price: Decimal

class VehicleCatListings(ORMBaseModel):
    code: str
    description: str
    listings: List[ CatListing ]

class ListOfCatListings(ORMBaseModel):
    List[ VehicleCatListings ]

But when I use the following route:但是当我使用以下路线时:

@app.get("/api/cat_no/{ff_no}/listings", response_model=schema.ListOfCatListings)
def getListings(ff_no: str, db: Session = Depends(databases.getDb)):
    listings = crud.catalogue.getListings(db, ff_no) #db request that returns data output as shown above

    if listings is None:
        raise HTTPException(status_code=404, detail="FF No catalogue listings not found")
    
    return listings

I get a blank object {} in return as if the pydantic model is ignoring the data somehow.我得到一个空白对象{}作为回报,好像 pydantic 模型以某种方式忽略了数据。 I am however finding it hard to debug.但是,我发现很难调试。

NB: I don't work for a place that sells rare Eastern European Car parts, I just used these as an example ;)注意:我不在一个出售稀有东欧汽车零件的地方工作,我只是以这些为例;)

Okay so after a lot of banging my head on a brick wall it turns out this is a very common problem and it's mentioned a few times on Stackoverflow already.好吧,在我用头撞了一堵砖墙之后,事实证明这是一个非常普遍的问题,并且已经在 Stackoverflow 上提到过几次。 The fault here is that:这里的错误在于:

class ListOfCatListings(ORMBaseModel):
    List[ VehicleCatListings ]

Should be:应该:

class ListOfCatListings(ORMBaseModel):
    __root__: List[ VehicleCatListings ]

This achieves what I needed.这达到了我所需要的。

I hope this helps someone else out.我希望这对其他人有所帮助。

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

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