簡體   English   中英

Pydantic model 字段名稱包含非字母數字字符

[英]Pydantic model with field names that have non-alphanumeric characters

我正在使用 FastAPI 並希望為以下請求數據 json 構建一個 pydantic model:

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

我這樣定義 model :

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

這自然會給出一個SyntaxError: invalid syntax for wind(%)

那么如何為鍵中包含非字母數字字符的 json 定義一個 pydantic model 呢?

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM