Closed as duplicate of#890
Description
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__])