1

我有一个包含数据库配置(键databases)(ServiceDatabaseOtherDatabase)的字典,并希望将其提取到里面的两个不同的子模型中。例子:

from dataclasses import asdict
from typing import *

from pydantic.dataclasses import dataclass


@dataclass
class ServiceDatabase:
    connect_string: str


@dataclass
class OtherDatabase:
    connect_string: str
    service: str


@dataclass
class PydConfigurator:
    """ Instead of the forward assignment as below, 
    I want implementation with Pydantic options or field or 
    any other object 
    """
    databases: List[Union[ServiceDatabase, OtherDatabase]]

    service_db: ServiceDatabase = None
    other_db: OtherDatabase = None

    def __post_init__(self):
        self.service_db = self.databases[0]
        self.other_db = self.databases[1]


data = {
    "databases": {
        "service_db": {
            "connect_string": "postgresql://{user}:{password}@{host}:{port}/{db_name}"
        },
        "other_db": {
            "connect_string": "postgresql://{user}:{password}@{host}:{port}/{db_name}",
            "service": "Any"
        }
    }
}

if __name__ == '__main__':
    # Example usage:
    config = PydConfigurator(**data)
    assert asdict(config.service_db) == data['databases']['service_db']

我想用 pydantic 的 Options 或 Schema 功能来实现它。在我看来,它会像service_db = Field(schema=ServiceDatabase, extract_from='database')

4

0 回答 0