flask-demo-api/flask_demo_api/ioc.py

48 lines
1.3 KiB
Python
Raw Normal View History

2024-04-15 04:02:47 +03:00
import redis # type: ignore
from config import Settings
from dishka import Container, Provider, Scope, make_container, provide
from protocols.repository import Repository
from repository.config import RedisSettings
from repository.redis import RedisRepository
from usecase.get import GetKey
class RedisSettingsProvider(Provider):
@provide(scope=Scope.APP)
def redis_settings(self) -> RedisSettings:
return RedisSettings()
class SettingsProvider(Provider):
@provide(scope=Scope.APP)
def main_settings(self, redis_settings: RedisSettings) -> Settings:
return Settings(redis=redis_settings)
class RedisPoolProvider(Provider):
@provide(scope=Scope.APP)
def get_redis_pool(self, redis_settings: RedisSettings) -> redis.Redis:
return redis.from_url(redis_settings.url, decode_responses=False)
class RepositoryProvider(Provider):
@provide(scope=Scope.REQUEST)
def get_db(self, redis_pool: redis.Redis) -> Repository:
return RedisRepository(redis_pool=redis_pool)
class UseCasesProvider(Provider):
scope = Scope.REQUEST
get = provide(GetKey)
def create_container() -> Container:
return make_container(
RedisSettingsProvider(),
SettingsProvider(),
RedisPoolProvider(),
RepositoryProvider(),
UseCasesProvider(),
)