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

8 python json pydantic fastapi

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

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

Run Code Online (Sandbox Code Playgroud)

我这样定义模型:

class Fuels(BaseModel):
    gas(euro/MWh): float
    kerosine(euro/MWh): float
    co2(euro/ton): int
    wind(%): int
Run Code Online (Sandbox Code Playgroud)

这自然会给出一个SyntaxError: invalid syntaxfor wind(%)

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

Yag*_*nci 20

使用别名,PydanticField使您能够使用别名。

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(%)")
Run Code Online (Sandbox Code Playgroud)