代码之家  ›  专栏  ›  技术社区  ›  Max Smirnov

如何在父权制环境中代表受歧视的工会?

  •  0
  • Max Smirnov  · 技术社区  · 1 年前

    我的项目有两种运行方式: webhook polling 因此,根据运行类型,它需要两种不同的配置。我从环境变量构造配置,其中 RUN_TYPE 变量(要么 "webhook" "polling" )区分跑步类型。每种运行类型都需要不同的变量集。

    以下是我试图用 pydantic / pydantic-settings :

    class WebhookSettings(BaseModel):
        run_type: Literal["webhook"]
        webhook_url: str
        webhook_path: str
    
    class PollingSettings(BaseModel):
        run_type: Literal["polling"]
        polling_interval: int
    
    class RunSettings(BaseSettings):
        run: Annotated[Union[WebhookSettings, PollingSettings], Field(discriminator="run_type")]
    

    但当我用环境运行它时: RUN_TYPE="polling" POLLING_INTERVAL=15 ,它失败了:

    pydantic_core._pydantic_core.ValidationError: 1 validation error for RunSettings
    run
      Field required [type=missing, input_value={}, input_type=dict]
        For further information visit https://errors.pydantic.dev/2.7/v/missing
    

    我的问题是什么?

    0 回复  |  直到 1 年前
        1
  •  2
  •   Rafael Marques    1 年前

    您正在使用 nested settings ,因此您需要正确设置:

    class WebhookSettings(BaseModel):
        run_type: Literal["webhook"]
        webhook_url: str
        webhook_path: str
    
    class PollingSettings(BaseModel):
        run_type: Literal["polling"]
        polling_interval: int
    
    class RunSettings(BaseSettings):
        model_config = SettingsConfigDict(env_nested_delimiter="__")
    
        run: Annotated[Union[WebhookSettings, PollingSettings], Field(discriminator="run_type")]
    

    对于webhook设置:

    os.environ["run__run_type"] = "webhook"
    os.environ["run__webhook_url"] = "http://test.com"
    os.environ["run__webhook_path"] = "v1/tests"
    
    settings = RunSettings()
    
    print(settings.model_dump())
    # {'run': {'run_type': 'webhook', 'webhook_url': 'http://test.com', 'webhook_path': 'v1/tests'}}
    

    轮询设置:

    os.environ["run__run_type"] = "polling"
    os.environ["run__polling_interval"] = "10"
    
    settings = RunSettings()
    
    print(settings.model_dump())
    # {'run': {'run_type': 'polling', 'polling_interval': 10}}
    
    推荐文章