【问题标题】:Pydantic and PurePosixPath from pathlib来自 pathlib 的 Pydantic 和 PurePosixPath
【发布时间】:2021-06-29 14:10:33
【问题描述】:

我有一个使用pydanticPath 字段构建的设置类。我需要这条路径作为 Unix 路径,因为它是在数据湖中导航

class Settings(BaseSettings):

    DATALAKE_MODEL_RESULT_PATH: Path

上述类的问题是,例如,如果我在 Windows 上,即使在 dotenv 文件中编写为 Unix(Path 类),该路径也会被视为 Windows 路径。

所以我尝试了

class Settings(BaseSettings):

    DATALAKE_MODEL_RESULT_PATH: PurePosixPath


但 pydantic 不认识它

ValidationError: 1 validation error for Settings
DATALAKE_MODEL_RESULT_PATH
  instance of PurePosixPath expected (type=type_error.arbitrary_type; expected_arbitrary_type=PurePosixPath)

也许我需要一个自定义字段?验证器?

【问题讨论】:

    标签: python pydantic


    【解决方案1】:

    您可以创建一个自定义验证器,它将强制路径转换为正确的格式:

    from pathlib import Path
    from pydantic import validator
    
    class Settings(BaseSettings):
    
        DATALAKE_MODEL_RESULT_PATH: Path
    
       @validator('DATALAKE_MODEL_RESULT_PATH')
       def validate_path(cls, v):
          return Path(v)
    

    这应该解决 windows 和 linux 之间的路径配置,但我不是 100% 确定。但是,可以在验证器函数中进行额外的验证 -> 因此,如果您选择扩充此解决方案,请将您的进一步工作放在那里。

    【讨论】:

      猜你喜欢
      • 2017-07-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-30
      • 2020-02-06
      • 2021-04-04
      • 2021-12-24
      • 2022-10-09
      相关资源
      最近更新 更多