【问题标题】:Pydantic model with field names that have non-alphanumeric characters具有非字母数字字符的字段名称的 Pydantic 模型
【发布时间】:2021-05-17 00:50:00
【问题描述】:

我正在使用 FastAPI 并想为以下请求数据 json 构建一个 pydantic 模型:

  {
    "gas(euro/MWh)": 13.4,
    "kerosine(euro/MWh)": 50.8,
    "co2(euro/ton)": 20,
    "wind(%)": 60
  }

我这样定义模型:

class Fuels(BaseModel):
    gas(euro/MWh): float
    kerosine(euro/MWh): float
    co2(euro/ton): int
    wind(%): int

这自然会为wind(%) 提供SyntaxError: invalid syntax

那么如何为键中包含非字母数字字符的 json 定义 pydantic 模型?

【问题讨论】:

    标签: python json fastapi pydantic


    【解决方案1】:

    使用别名,Pydantic 的Field 让您能够使用别名。

    from pydantic import BaseModel, Field
    
    
    class Fuels(BaseModel):
        gas: float = Field(..., alias="gas(euro/MWh)")
        kerosine: float = Field(..., alias="kerosine(euro/MWh)") 
        co2: int = Field(..., alias="co2(euro/ton)")
        wind: int = Field(..., alias="wind(%)")
    

    【讨论】:

    • 如何从别名中获取类的字段名?可能吗?天然气(欧元/兆瓦时)-> 天然气
    猜你喜欢
    • 2018-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-17
    • 2016-05-22
    • 1970-01-01
    • 2021-10-21
    相关资源
    最近更新 更多