flask-demo-api/flask_demo_api/ioc.py

58 lines
1.7 KiB
Python
Raw Permalink Normal View History

2024-04-16 04:48:10 +03:00
import os
2024-04-15 04:02:47 +03:00
import redis # type: ignore
from dishka import Container, Provider, Scope, make_container, provide
2024-04-16 01:03:02 +03:00
from flask_demo_api.config import Settings
from flask_demo_api.protocols.repository import Repository
from flask_demo_api.repository.config import RedisSettings
from flask_demo_api.repository.redis import RedisRepository
from flask_demo_api.usecase.add import PostKey
from flask_demo_api.usecase.delete import DelKey
from flask_demo_api.usecase.get import GetKey
from flask_demo_api.usecase.put import PutKey
2024-04-15 04:02:47 +03:00
class RedisSettingsProvider(Provider):
@provide(scope=Scope.APP)
def redis_settings(self) -> RedisSettings:
2024-04-16 04:48:10 +03:00
url = os.getenv("REDISURL") or "redis://localhost:6379/0"
return RedisSettings(url=url)
2024-04-15 04:02:47 +03:00
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)
2024-04-15 09:32:17 +03:00
post = provide(PostKey)
put = provide(PutKey)
2024-04-16 01:03:02 +03:00
delete = provide(DelKey)
2024-04-15 04:02:47 +03:00
def create_container() -> Container:
return make_container(
RedisSettingsProvider(),
SettingsProvider(),
RedisPoolProvider(),
RepositoryProvider(),
UseCasesProvider(),
)