字段名称包含非字母数字字符的 Pydantic 模型

问题描述

我正在使用 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

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

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

解决方法

使用别名,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(%)")