8000 Config confuse · Issue #877 · ets-labs/python-dependency-injector · GitHub
[go: up one dir, main page]

Skip to content
Config confuse #877
Closed as duplicate of#890
Closed as duplicate of#890
@xuexiaolei1997

Description

@xuexiaolei1997

Under normal circumstances, the following code can be run:

class Container(containers.DeclarativeContainer):
    
    config: CommonConfig = providers.Configuration()

    # redis pool
    redis_pool = providers.Resource(
        init_redis_pool,
        config=config
    )

    async def init_resources(self):
        super().init_resources()

    async def shutdown_resources(self):
        redis_client = await self.redis_pool()
        await redis_client.close()

But I want to write the code in the following way:

class Container(containers.DeclarativeContainer):
    
    config: CommonConfig = providers.Configuration()

    # redis pool
    redis_pool = providers.Resource(
        init_redis_pool,
        redis_config=config.redis
    )

    async def init_resources(self):
        super().init_resources()

    async def shutdown_resources(self):
        redis_client = await self.redis_pool()
        await redis_client.close()

In this case, an error occurred:
***(Pydantic.BaseModel) object has no attribute 'get'
Here's how I declare config:

import yaml
from pydantic import BaseModel, Field

class RedisConfig(BaseModel):
    host: str
    port: int
    password: str
    db: str
    max_connections: int = Field(..., ge=2, le=20)

class CommonConfig(BaseModel):
    redis: RedisConfig
    log_level: str


def load_config(config_path: str) -> CommonConfig:
    with open(config_path, "r") as f:
        config = yaml.safe_load(f)
    return CommonConfig(**config)

_config = load_config(config_path)
_container = Container(config=_config)
await _container.init_resources()
_container.wire(modules=[__name__])

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      0