Skip to content

Config confuse #877

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
xuexiaolei1997 opened this issue Apr 15, 2025 · 1 comment
Open

Config confuse #877

xuexiaolei1997 opened this issue Apr 15, 2025 · 1 comment

Comments

@xuexiaolei1997
Copy link

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__])
@xuexiaolei1997
Copy link
Author

What I understand is that when I declare a class, after passing in the config variable, it will be overridded, so it can be called directly. But from the results, config.redis doesn't dynamically modify providers.Resource based on config changes, which I'm puzzled about.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant