Coverage for src/kwai/core/events/dependencies.py: 0%
34 statements
« prev ^ index » next coverage.py v7.7.1, created at 2024-01-01 00:00 +0000
« prev ^ index » next coverage.py v7.7.1, created at 2024-01-01 00:00 +0000
1"""Module that defines the dependencies for events."""
3import contextlib
5from typing import AsyncGenerator
7import inject
9from inject import Binder
11from kwai.core.db.database import Database
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
19@contextlib.asynccontextmanager
20@inject.autoparams()
21async def create_database(
22 settings: Settings,
23) -> AsyncGenerator[Database, None]:
24 """Create the database dependency."""
25 database = Database(settings.db)
26 try:
27 yield database
28 finally:
29 await database.close()
32@inject.autoparams()
33def create_template_engine(
34 settings: Settings,
35) -> TemplateEngine:
36 """Create the template engine dependency."""
37 return Jinja2Engine(website=settings.website)
40@inject.autoparams()
41def create_mailer(settings: Settings) -> Mailer:
42 """Create the mailer dependency."""
43 mailer = SmtpMailer(
44 host=settings.email.host,
45 port=settings.email.port,
46 ssl_=settings.email.ssl,
47 tls=settings.email.tls,
48 )
49 mailer.connect()
50 if settings.email.user:
51 mailer.login(settings.email.user, settings.email.password)
52 return mailer
55def _configure_dependencies(binder: Binder):
56 binder.bind_to_provider(Settings, get_settings)
57 binder.bind_to_provider(Database, create_database)
58 binder.bind_to_provider(TemplateEngine, create_template_engine)
59 binder.bind_to_provider(Mailer, create_mailer)
62def configure():
63 """Configure the dependency injection system.
65 Note: only use dependency injection for injecting dependencies into tasks. A task
66 method is used as entry from outside. DI makes it possible to pass dependencies to
67 this method. Regular constructors should be used for injecting dependencies into
68 domain classes.
69 """
70 inject.configure(_configure_dependencies)