Coverage for kwai/core/dependencies.py: 84%
31 statements
« prev ^ index » next coverage.py v7.3.0, created at 2023-09-05 17:55 +0000
« prev ^ index » next coverage.py v7.3.0, created at 2023-09-05 17:55 +0000
1"""Module that defines a dependency injector container.
3Auto-wiring is avoided. It should be clear why and when a class is loaded.
4"""
6from lagom import Container, ExplicitContainer, Singleton, dependency_definition
7from redis.asyncio import Redis
9from kwai.core.db.database import Database
10from kwai.core.events.bus import Bus
11from kwai.core.events.redis_bus import RedisBus
12from kwai.core.mail.mailer import Mailer
13from kwai.core.mail.smtp_mailer import SmtpMailer
14from kwai.core.settings import Settings, get_settings
15from kwai.core.template.jinja2_engine import Jinja2Engine
16from kwai.core.template.template_engine import TemplateEngine
18container = ExplicitContainer()
20container[Settings] = Singleton(get_settings)
21container[TemplateEngine] = lambda c: Jinja2Engine(
22 c[Settings].template.path, website=c[Settings].website
23)
26@dependency_definition(container)
27def create_database(c: Container) -> Database:
28 """Create the database dependency."""
29 database = Database(c[Settings].db)
30 return database
33@dependency_definition(container)
34def create_mailer(c: Container) -> Mailer:
35 """Create the mailer dependency."""
36 mailer = SmtpMailer(
37 host=c[Settings].email.host,
38 port=c[Settings].email.port,
39 ssl_=c[Settings].email.ssl,
40 tls=c[Settings].email.tls,
41 )
42 mailer.connect()
43 if c[Settings].email.user:
44 mailer.login(c[Settings].email.user, c[Settings].email.password)
45 return mailer
48@dependency_definition(container)
49def create_redis(c: Container) -> Redis:
50 """Create the redis dependency."""
51 redis_settings = c[Settings].redis
52 return Redis(
53 host=redis_settings.host,
54 port=redis_settings.port or 6379,
55 password=redis_settings.password,
56 )
59@dependency_definition(container)
60def create_event_bus(c: Container) -> Bus:
61 """Create the event bus dependency."""
62 return RedisBus(c[Redis])