【问题标题】:In FastAPI / Pydantic how can I define a return dictionary class that returns a dictionary of tuples在 FastAPI / Pydantic 中,我如何定义一个返回元组字典的返回字典类
【发布时间】:2021-05-02 12:43:22
【问题描述】:

我有一个 FastAPI 请求,它返回这样的 JSON

{
  "1": [
    [
      "HH",
      "0"
    ],
    [
      "DD",
      "0"
    ]
  ]
}

基本上,它是一个以票号为键(此处为“1”)和一个元组列表(每个为两个字符串)的字典。

有没有办法将此结构转换为 Pydantic 模型,以便我可以将其与 FastAPI 一起用作响应模型?

【问题讨论】:

    标签: fastapi pydantic


    【解决方案1】:

    这可以通过定义custom root type 并使用conlist 来实现:

    from typing import Dict, List
    
    import uvicorn
    from fastapi import FastAPI
    from pydantic import BaseModel, conlist
    
    app = FastAPI()
    
    
    class ResponseModel(BaseModel):
        __root__: Dict[str, List[conlist(item_type=str, min_items=2, max_items=2)]]
    
    
    @app.get("/result", response_model=ResponseModel)
    async def get_result():
        a = {"1": [["DD", "0"], ["HH", "0"]]}
        return ResponseModel.parse_obj(a)
    
    
    if __name__ == "__main__":
        uvicorn.run(app, host="0.0.0.0", port=8000)
    

    【讨论】:

    • 对我来说,这是行不通的。 {'1': [['DD', '0]), ['HH', '0']]} 导致错误 pydantic.error_wrappers.ValidationError: 1 validation error for ResponseModel response -> root -> 1 unhashable type: 'list' (type=type_error) 并将内部列表转换为元组给出我的错误:pydantic.error_wrappers.ValidationError: ResponseModel 响应的 2 个验证错误 -> root -> 1 -> 0 str type expected (type=type_error.str) response -> root -> 1 -> 预期 1 个 str 类型 (type=type_error.str)
    猜你喜欢
    • 2022-06-26
    • 1970-01-01
    • 2020-05-02
    • 1970-01-01
    • 2019-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-16
    相关资源
    最近更新 更多