Exemple #1
0
    def test(self):
        container = containers.DynamicContainer()
        container.from_schema(
            {
                'version': '1',
                'container': {
                    'provider1': {
                        'provider': 'Factory',
                        'provides': 'list',
                        'args': [1, 2, 3],
                    },
                    'provider2': {
                        'provider': 'Factory',
                        'provides': 'dict',
                        'kwargs': {
                            'one': 'container.provider1',
                            'two': 2,
                        },
                    },
                },
            }, )

        self.assertIsInstance(container.provider1, providers.Factory)
        self.assertIs(container.provider1.provides, list)
        self.assertEqual(container.provider1.args, (1, 2, 3))

        self.assertIsInstance(container.provider2, providers.Factory)
        self.assertIs(container.provider2.provides, dict)
        self.assertEqual(container.provider2.kwargs, {
            'one': container.provider1,
            'two': 2
        })
Exemple #2
0
    def test(self):
        container = containers.DynamicContainer()
        container.from_yaml_schema(f'{_SAMPLES_DIR}/schemasample/container-multiple.yml')
        container.core.config.from_dict({
            'database': {
                'dsn': ':memory:',
            },
            'aws': {
                'access_key_id': 'KEY',
                'secret_access_key': 'SECRET',
            },
            'auth': {
                'token_ttl': 3600,
            },
        })

        # User service
        user_service1 = container.services.user()
        user_service2 = container.services.user()
        self.assertIsInstance(user_service1, UserService)
        self.assertIsInstance(user_service2, UserService)
        self.assertIsNot(user_service1, user_service2)

        self.assertIsInstance(user_service1.db, sqlite3.Connection)
        self.assertIsInstance(user_service2.db, sqlite3.Connection)
        self.assertIs(user_service1.db, user_service2.db)

        # Auth service
        auth_service1 = container.services.auth()
        auth_service2 = container.services.auth()
        self.assertIsInstance(auth_service1, AuthService)
        self.assertIsInstance(auth_service2, AuthService)
        self.assertIsNot(auth_service1, auth_service2)

        self.assertIsInstance(auth_service1.db, sqlite3.Connection)
        self.assertIsInstance(auth_service2.db, sqlite3.Connection)
        self.assertIs(auth_service1.db, auth_service2.db)
        self.assertIs(auth_service1.db, container.gateways.database_client())
        self.assertIs(auth_service2.db, container.gateways.database_client())

        self.assertEqual(auth_service1.token_ttl, 3600)
        self.assertEqual(auth_service2.token_ttl, 3600)

        # Photo service
        photo_service1 = container.services.photo()
        photo_service2 = container.services.photo()
        self.assertIsInstance(photo_service1, PhotoService)
        self.assertIsInstance(photo_service2, PhotoService)
        self.assertIsNot(photo_service1, photo_service2)

        self.assertIsInstance(photo_service1.db, sqlite3.Connection)
        self.assertIsInstance(photo_service2.db, sqlite3.Connection)
        self.assertIs(photo_service1.db, photo_service2.db)
        self.assertIs(photo_service1.db, container.gateways.database_client())
        self.assertIs(photo_service2.db, container.gateways.database_client())

        self.assertIs(photo_service1.s3, photo_service2.s3)
        self.assertIs(photo_service1.s3, container.gateways.s3_client())
        self.assertIs(photo_service2.s3, container.gateways.s3_client())
Exemple #3
0
    def test_wire(self):
        sub = containers.DynamicContainer()
        sub.int_object = providers.Object(1)

        container = containers.DynamicContainer()
        container.config = providers.Configuration()
        container.service = providers.Factory(Service)
        container.sub = sub

        container.wire(
            modules=[module],
            packages=[package],
        )
        self.addCleanup(container.unwire)

        service = module.test_function()
        self.assertIsInstance(service, Service)
Exemple #4
0
def container():
    sub = containers.DynamicContainer()
    sub.int_object = providers.Object(1)

    container = containers.DynamicContainer()
    container.config = providers.Configuration()
    container.service = providers.Factory(Service)
    container.sub = sub

    container.wire(
        modules=[module],
        packages=[package],
    )

    yield container

    container.unwire()
        class Container(containers.DeclarativeContainer):
            class Container1(containers.DeclarativeContainer):
                pass

            class Container2(containers.DeclarativeContainer):
                pass

            Container3 = containers.DynamicContainer()
def test_parent_deepcopy(provider):
    container = containers.DynamicContainer()
    container.name = provider

    copied = providers.deepcopy(container)

    assert container.name.parent is container
    assert copied.name.parent is copied

    assert container is not copied
    assert container.name is not copied.name
    assert container.name.parent is not copied.name.parent
    def test_parent_deepcopy(self):
        container = containers.DynamicContainer()
        provider = providers.Container(TestCore)
        container.name = provider

        copied = providers.deepcopy(container)

        self.assertIs(container.name.parent, container)
        self.assertIs(copied.name.parent, copied)

        self.assertIsNot(container, copied)
        self.assertIsNot(container.name, copied.name)
        self.assertIsNot(container.name.parent, copied.name.parent)
Exemple #8
0
    def test(self):
        container = containers.DynamicContainer()
        container.from_yaml_schema(f'{_SAMPLES_DIR}/schemasample/container-boto3-session.yml')
        container.config.from_dict(
            {
                'aws_access_key_id': 'key',
                'aws_secret_access_key': 'secret',
                'aws_session_token': 'token',
                'aws_region_name': 'us-east-1',
            },
        )

        self.assertEqual(container.s3_client().__class__.__name__, 'S3')
        self.assertEqual(container.sqs_client().__class__.__name__, 'SQS')
Exemple #9
0
class Services(containers.DeclarativeContainer):
    """IoC container of business service componant providers"""
    dynamic = containers.DynamicContainer()

    @staticmethod
    def add(stype: ServiceType, service, name: str = None, *args, **kwargs):
        """
        registers object or function to Services.dynamic
        :param name: service name. if None, __name__ will be used
        """
        name = service.__name__ if name is None else name
        dynamic_provider = stype.value(service, *args, **kwargs)
        containers.DynamicContainer.__setattr__(Services.dynamic, name,
                                                dynamic_provider)
Exemple #10
0
    def test_no_yaml_installed(self):
        @contextlib.contextmanager
        def no_yaml_module():
            containers.yaml = None
            yield
            containers.yaml = yaml

        container = containers.DynamicContainer()
        with no_yaml_module():
            with self.assertRaises(errors.Error) as error:
                container.from_yaml_schema('./no-yaml-installed.yml')

        self.assertEqual(
            error.exception.args[0],
            'Unable to load yaml schema - PyYAML is not installed. '
            'Install PyYAML or install Dependency Injector with yaml extras: '
            '"pip install dependency-injector[yaml]"',
        )
Exemple #11
0
    def test_with_loader(self):
        container = containers.DynamicContainer()

        with tempfile.TemporaryDirectory() as tmp_dir:
            schema_path = os.path.join(tmp_dir, 'schema.yml')
            with open(schema_path, 'w') as file:
                file.write("""
                version: "1"
                container:
                  provider:
                    provider: Factory
                    provides: list
                    args: [1, 2, 3]
                """)

            container.from_yaml_schema(schema_path, loader=yaml.Loader)

        self.assertIsInstance(container.provider, providers.Factory)
        self.assertIs(container.provider.provides, list)
        self.assertEqual(container.provider.args, (1, 2, 3))
Exemple #12
0
    def test(self):
        container = containers.DynamicContainer()

        with tempfile.TemporaryDirectory() as tmp_dir:
            schema_path = os.path.join(tmp_dir, 'schema.json')
            with open(schema_path, 'w') as file:
                file.write(
                    json.dumps(
                        {
                            'version': '1',
                            'container': {
                                'provider1': {
                                    'provider': 'Factory',
                                    'provides': 'list',
                                    'args': [1, 2, 3],
                                },
                                'provider2': {
                                    'provider': 'Factory',
                                    'provides': 'dict',
                                    'kwargs': {
                                        'one': 'container.provider1',
                                        'two': 2,
                                    },
                                },
                            },
                        },
                        indent=4,
                    ), )

            container.from_json_schema(schema_path)

        self.assertIsInstance(container.provider1, providers.Factory)
        self.assertIs(container.provider1.provides, list)
        self.assertEqual(container.provider1.args, (1, 2, 3))

        self.assertIsInstance(container.provider2, providers.Factory)
        self.assertIs(container.provider2.provides, dict)
        self.assertEqual(container.provider2.kwargs, {
            'one': container.provider1,
            'two': 2
        })
Exemple #13
0
    def test(self):
        container = containers.DynamicContainer()

        with tempfile.TemporaryDirectory() as tmp_dir:
            schema_path = os.path.join(tmp_dir, 'schema.yml')
            with open(schema_path, 'w') as file:
                file.write("""
                version: "1"
                container:
                  provider1:
                    provider: Factory
                    provides: list
                    args:
                      - 1
                      - 2
                      - 3
                  provider2:
                    provider: Factory
                    provides: dict
                    kwargs:
                      one: container.provider1
                      two: 2
                """)

            container.from_yaml_schema(schema_path)

        self.assertIsInstance(container.provider1, providers.Factory)
        self.assertIs(container.provider1.provides, list)
        self.assertEqual(container.provider1.args, (1, 2, 3))

        self.assertIsInstance(container.provider2, providers.Factory)
        self.assertIs(container.provider2.provides, dict)
        self.assertEqual(container.provider2.kwargs, {
            'one': container.provider1,
            'two': 2
        })
Exemple #14
0
import dependency_injector.containers as containers
import dependency_injector.providers as providers
import dependency_injector.errors as errors


class SequenceProvider(providers.Factory):
    """Sequence factory.

    Can provide only sequence objects.
    """

    provided_type = collections.Sequence


sequences_container = containers.DynamicContainer()
sequences_container.provider_type = SequenceProvider


if __name__ == '__main__':
    try:
        sequences_container.object_provider = providers.Factory(object)
    except errors.Error as exception:
        print exception
        # <dependency_injector.containers.DynamicContainer object at
        # 0x107820ed0> can contain only <class '__main__.SequenceProvider'>
        # instances

    try:
        sequences_container.object_provider = SequenceProvider(object)
    except errors.Error as exception:
Exemple #15
0
        if not dc:
            return None

        try:
            return getattr(DataTypeContainer, dc["class"])().from_dict(dc)

        except KeyError:
            return None

    def _apply_transformations(self, value: Any):
        result = value
        for f in self.transformations:
            result = f(result)

        return result

    def __getstate__(self) -> dict:
        return {"class": str(self)}

    def __setstate__(self, new_state: dict):
        pass

    def __reduce__(self):
        return (DataType, (), self.__getstate__())

    def __str__(self) -> str:
        return type(self).__name__


DataTypeContainer = containers.DynamicContainer()
Exemple #16
0
    ...


def populate_container(container, providers_config):
    for provider_name, provider_info in providers_config.items():
        provided_cls = globals().get(provider_info['class'])
        provider_cls = getattr(providers, provider_info['provider_class'])
        setattr(container, provider_name, provider_cls(provided_cls))


if __name__ == '__main__':
    services_config = {
        'user': {
            'class': 'UserService',
            'provider_class': 'Factory',
        },
        'auth': {
            'class': 'AuthService',
            'provider_class': 'Factory',
        },
    }
    services = containers.DynamicContainer()

    populate_container(services, services_config)

    user_service = services.user()
    auth_service = services.auth()

    assert isinstance(user_service, UserService)
    assert isinstance(auth_service, AuthService)
 def test_parent_name(self):
     container = containers.DynamicContainer()
     provider = providers.DependenciesContainer()
     container.name = provider
     self.assertEqual(provider.parent_name, 'name')
Exemple #18
0
                        category_name
                    )

                    image_full_path = os.path.join(dataset_dir, image_filename)

                    x.append(
                        self.get_x_type().convert_to_expected_format(image_full_path)
                    )
                    y.append(category_data)

                except Exception as err:
                    print(err)

        else:
            raise ValueError(f"Invalid organization value: {self.get_organization()}")

        dataset.x = np.array(x)
        dataset.y = np.array(y)

        return dataset


DatasetIORegistry = containers.DynamicContainer()
setattr(DatasetIORegistry, NpzDatasetIO.Label, providers.Factory(NpzDatasetIO))
setattr(DatasetIORegistry, TxtDatasetIO.Label, providers.Factory(TxtDatasetIO))
setattr(
    DatasetIORegistry,
    CategoricalImgDatasetIO.Label,
    providers.Factory(CategoricalImgDatasetIO),
)
Exemple #19
0
 def test_dynamic(self):
     container: containers.Container = containers.DynamicContainer()
     self.assertIsInstance(container, containers.Container)
 def test_parent_name(self):
     container = containers.DynamicContainer()
     provider = providers.Container(TestCore)
     container.name = provider
     self.assertEqual(provider.parent_name, 'name')
def container():
    return containers.DynamicContainer()
Exemple #22
0
        def __init__(self, config, main, common_ioc_factory, message_bus_ioc_factory, combinator_ioc_factory, lexicomb_ioc_factory, state_machine_ioc_factory, lexical_state_machine_ioc_factory, interpreter_state_machine_ioc_factory):
            self.__instance = containers.DynamicContainer()
            logging_provider = IocUtil.create_basic_log_adapter(providers, "bbpyp.lexicomb_engine")
            common_ioc = common_ioc_factory(config=config, source_format_rules={
                ":=": {"format": [(r"\s*{}\s*", r"{} ")]},
                "+": {"format": [(r"\s*{}\s*", r" {} ")]},
                "-": {"format": [(r"\s*{}\s*", r" {} ")]},
                "*": {"format": [(r"\s*{}\s*", r" {} ")]},
                "/": {"format": [(r"\s*{}\s*", r" {} ")]},
                ";": {"format": [(r"\s*{}\s*", r"{}" + linesep)]},
                "{": {"format": [(r"\s*{}\s*", r"{}" + linesep)], "indent_delta": IndentDelta.INCREASE},
                "}": {"format": [(rf"\s*{linesep}{{{{1}}}}(\s*){{}}\s*", linesep + r"\1{}" + linesep)], "indent_delta": IndentDelta.DECREASE},
                "return": {"format": [(rf"\s*{linesep}{{{{1}}}}(\s*){{}}\s*", linesep + r"\1{} ")]}
            }).build()

            message_bus_ioc = message_bus_ioc_factory(
                config=config,
                common_ioc=common_ioc).build()
            combinator_ioc = combinator_ioc_factory(
                common_ioc=common_ioc).build()
            lexicomb_ioc = lexicomb_ioc_factory(
                config=config,
                common_ioc=common_ioc,
                combinator_ioc=combinator_ioc).build()
            state_machine_ioc = state_machine_ioc_factory()
            lexical_state_machine_ioc = lexical_state_machine_ioc_factory(
                config=config,
                common_ioc=common_ioc,
                state_machine_ioc=state_machine_ioc).build()
            interpreter_state_machine_ioc = interpreter_state_machine_ioc_factory(
                config=config,
                common_ioc=common_ioc,
                state_machine_ioc=state_machine_ioc).build()

            lexical_actions_provider = providers.Singleton(
                LexicalActions,
                logger=logging_provider,
                lexer=lexicomb_ioc.lexer_provider,
                queue_service=common_ioc.queue_service_provider,
                notification_service=common_ioc.notification_service_provider)

            interpreter_actions_provider = providers.Singleton(
                InterpreterActions,
                logger=logging_provider,
                parser_combinator=lexicomb_ioc.parser_provider,
                queue_service=common_ioc.queue_service_provider,
                notification_service=common_ioc.notification_service_provider)

            lexical_state_machine_ioc.lexical_actions_provider.provided_by(
                lexical_actions_provider)

            interpreter_state_machine_ioc.interpreter_actions_provider.provided_by(
                interpreter_actions_provider)

            lexicomb_pub_sub_client_provider = providers.DelegatedFactory(
                LexicombPubSubClient,
                logger=logging_provider,
                queue_service=common_ioc.queue_service_provider,
                notification_service=common_ioc.notification_service_provider,
                message_factory=message_bus_ioc.message_factory_provider,
                file_stream_service=common_ioc.file_stream_service_provider,
                context_service=common_ioc.context_service_provider,
                async_service=common_ioc.async_service_provider)

            create_client = providers.DelegatedCallable(
                self.__create_lexicomb_client,
                logger=logging_provider,
                pub_sub=message_bus_ioc.pub_sub_provider,
                message_pipe_line_builder=message_bus_ioc.message_pipe_line_builder_provider,
                pub_sub_client_factory=lexicomb_pub_sub_client_provider,
                lexical_state_machine=lexical_state_machine_ioc.lexical_state_machine_provider,
                interpreter_state_machine=interpreter_state_machine_ioc.interpreter_state_machine_provider)

            self.__instance.lexicomb_ioc = lexicomb_ioc

            self.__instance.main = providers.Callable(
                main, create_client=create_client, pub_sub=message_bus_ioc.pub_sub_provider, async_service=common_ioc.async_service_provider, metric_service=common_ioc.metric_service_provider)
Exemple #23
0
# Core
import os
from jinja2 import Environment, FileSystemLoader

# Dependency injector
from dependency_injector import containers
from dependency_injector import providers

app = None
db = None
bcrypt = None
jinja = Environment(loader=FileSystemLoader(
    os.path.join(os.path.dirname(__file__), 'templates')))

# User context
user_context = containers.DynamicContainer()


def init_user_app(
    app_instance,
    db_instance,
    bcrypt_instance,
):
    global app
    global db
    global bcrypt

    app = app_instance
    db = db_instance
    bcrypt = bcrypt_instance
class Kernel:
    """The application initializer. It loads all the components and then let the control to the bundles"""
    inject_bindings = {}
    config = None

    container = containers.DynamicContainer()

    def load_configuration(self, configuration_file, parameters_file):
        """Parse the configuration and put it into the kernel and container"""
        self.console.log("Parsing configuration...")
        try:
            self.config = load_configuration(
                configuration_file_path=configuration_file,
                parameters_file_path=parameters_file,
                bundles=self.bundles
            )
            Kernel.config = self.config
            self.container.configuration = Configuration()
            self.console.log("Configuration [bold green]OK[/]")
        except ValidationError as ex:
            self.console.rule("[bold red]Configuration error")
            for error in ex.errors():
                loc = "[yellow] -> [/]".join([f"[cyan]{i}[/]" for i in error["loc"]])
                self.console.print(f"{loc}: {error['msg']} (type={error['type']})")
            sys.exit()

    def kernel_ready_event(self, _event):
        """Seeing this message is the proof that the events are working"""
        table = Table(show_header=False, style="bold green")
        table.add_row("Kernel ready")
        self.console.print(table)

    def kernel_shutdown_event(self, _event):
        """Seeing this message is the proof that the events are working"""
        table = Table(show_header=False, style="bold cyan")
        table.add_row("Kernel shutdown")
        self.console.print(table)

    def register_event_listeners(self):
        """Add all kernel and bundles listeners"""
        self.console.log("Registering event listeners")
        self.event_manager.add_listener(event=KernelReadyEvent, listener=self.kernel_ready_event)
        self.event_manager.add_listener(event=KernelShutdownEvent, listener=self.kernel_shutdown_event)
        for bundle in self.bundles:
            if hasattr(bundle, 'event_listeners'):
                for event_type, listener in bundle.event_listeners:
                    self.event_manager.add_listener(event=event_type, listener=listener)
                event_list = ', '.join(
                    [f'[bright_magenta]{event_type.__name__}[/]' for event_type, _ in bundle.event_listeners]
                )
                self.console.log(f"Registered events for [bold cyan]{bundle.__class__.__name__}[/]: {event_list}")
        self.console.log("Events [bold green]OK[/]")

    def build_dependency_container(self):
        """Build the kernel and bundles service containers"""
        self.console.log("Building dependency container")
        for bundle in self.bundles:
            if hasattr(bundle, 'injection_bindings'):
                for class_type, provider in bundle.injection_bindings.items():
                    setattr(self.container, class_type, provider)
        self.console.log("Dependency container built")

    def register_services(self):
        """Register the bundles services but not run them yet, it will be done later"""
        self.console.log("Registering services")
        for bundle in self.bundles:
            if hasattr(bundle, 'services'):
                for service_name, service_function, args, kwargs in bundle.services:
                    self.console.log(f"Adding {service_name}")
                    self.service_runner.add_service(
                        name=service_name,
                        function=service_function,
                        args=args,
                        kwargs=kwargs
                    )

    def __init__(self,
                 environment,
                 bundles,
                 configuration_file="config/config.yml",
                 parameters_file="config/parameters.yml"):
        self.console = Console()
        self.console.log(f"Running environment [bold green]{environment}[/]")
        self.bundles = bundles
        self.environment = environment
        self.event_manager = EventManager()
        self.service_runner = ProcessServiceRunner()
        self.shutting_down = False

        # Signals
        signal.signal(signal.SIGINT, self._signal_handler)
        signal.signal(signal.SIGTERM, self._signal_handler)

        with self.console.status("[bold green]Booting kernel..."):
            self.load_configuration(configuration_file=configuration_file, parameters_file=parameters_file)
            self.register_event_listeners()
            self.event_manager.dispatch(ConfigurationReadyEvent(configuration=self.config))
            self.build_dependency_container()
            self.event_manager.dispatch(KernelReadyEvent())
            self.register_services()

        self.service_runner.run()

    def _signal_handler(self, _os_signal, _frame):
        self.shutdown()

    def shutdown(self):
        """Start the kernel shutdown process. It will stopp all services and the exit"""
        if not self.shutting_down:
            table = Table(show_header=False, style="bold red")
            table.add_row("Shutdown signal received, press ctrl + c to kill the process")
            self.console.print(table)
            self.shutting_down = True
            self.service_runner.shutdown()
        else:
            self.console.log("[bold red]Killing...[/]")
            self.service_runner.kill()

    def wait(self):
        """Wait until all services are done"""
        self.service_runner.wait()

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        self.event_manager.dispatch(KernelShutdownEvent())
def test_parent_name_is_none():
    container = containers.DynamicContainer()
    assert container.parent_name is None
Exemple #26
0
# -*- coding: utf-8

# Dependency injector
from dependency_injector import containers
from dependency_injector import providers

app = None
db = None

# Messaging context
messaging_context = containers.DynamicContainer()


def init_messaging_app(
    app_instance,
    db_instance,
):
    global app
    global db

    app = app_instance
    db = db_instance

    # Stores
    from .stores.channel_store import ChannelStore
    from .stores.message_store import MessageStore

    # Query sets
    from .query_sets.channel_query import ChannelQuery
    from .query_sets.message_query import MessageQuery
    from .query_sets.channel_user_query import ChannelUserQuery
Exemple #27
0
 def test_parent_name_is_none(self):
     container = containers.DynamicContainer()
     self.assertIsNone(container.parent_name)
Exemple #28
0
class Kernel:
    """The application initializer. It loads all the components and then let the control to the bundles"""
    inject_bindings = {}
    config = None

    container = containers.DynamicContainer()

    def load_configuration(self, configuration_file, parameters_file):
        """Parse the configuration and put it into the kernel and container"""
        self.console.log("Parsing configuration...")
        try:
            self.config = load_configuration(
                configuration_file_path=configuration_file,
                parameters_file_path=parameters_file,
                bundles=self.bundles)
            Kernel.config = self.config
            self.container.configuration = Configuration()
            self.console.log("Configuration [bold green]OK[/]")
        except ValidationError as ex:
            self.console.rule("[bold red]Configuration error")
            for error in ex.errors():
                loc = "[yellow] -> [/]".join(
                    [f"[cyan]{i}[/]" for i in error["loc"]])
                self.console.print(
                    f"{loc}: {error['msg']} (type={error['type']})")
            sys.exit()

    def kernel_ready_event(self, _event):
        """Seeing this message is the proof that the events are working"""
        table = Table(show_header=False, style="bold green")
        table.add_row("Kernel ready")
        self.console.print(table)

    def kernel_shutdown_event(self, _event):
        """Seeing this message is the proof that the events are working"""
        table = Table(show_header=False, style="bold cyan")
        table.add_row("Kernel shutdown")
        self.console.print(table)

    def register_event_listeners(self, config_only: bool = False):
        """Add all kernel and bundles listeners"""
        config_text = "for ConfigurationReadyEvent only" if config_only else "for all other events"
        self.console.log(f"Registering event listeners {config_text}")
        for bundle in self.bundles:
            event_list = self.register_event_listeners_for_bundle(
                bundle, config_only=config_only)
            self.log_event_listeners_registered_for_bundle(bundle, event_list)
        # Blinker does not duplicate signals so there is probably no reason to worry about adding listeners
        # twice, but anyways checking makes sense to me.
        if not config_only:
            self.event_manager.add_listener(event=KernelReadyEvent,
                                            listener=self.kernel_ready_event)
            self.event_manager.add_listener(
                event=KernelShutdownEvent, listener=self.kernel_shutdown_event)
        self.console.log("Events [bold green]OK[/]")

    def register_event_listeners_for_bundle(self,
                                            bundle: object,
                                            config_only: bool = False):
        """Add bundles' event listeners"""
        registered_listeners = []
        for event_type, listener in getattr(bundle, 'event_listeners', []):
            is_config_event = issubclass(event_type, ConfigurationReadyEvent)
            must_register = is_config_event if config_only else not is_config_event
            if not must_register:
                continue
            self.event_manager.add_listener(event=event_type,
                                            listener=listener)
            registered_listeners.append(event_type)
        return registered_listeners

    def log_event_listeners_registered_for_bundle(
            self, bundle: object, registered_listeners: List[str]):
        """Display in the console the added event listeners"""
        if registered_listeners:
            event_list = ', '.join([
                f'[bright_magenta]{event_type.__name__}[/]'
                for event_type in registered_listeners
            ])
            self.console.log(
                f"Registered events for [bold cyan]{bundle.__class__.__name__}[/]: {event_list}"
            )

    def build_dependency_container(self):
        """Build the kernel and bundles service containers"""
        self.console.log("Building dependency container")
        wire_modules = []
        for bundle in self.bundles:
            if hasattr(bundle, 'injection_bindings'):
                for class_type, provider in bundle.injection_bindings.items():
                    # A container provider is useful when a container has dependencies on other containers. Just provide
                    # the container class as an easy way to use the defaults
                    if isinstance(provider, types.FunctionType):
                        # We use a function instead of directly the Provider to ensure that the dependencies are using
                        # exactly the same container (and not other instance). Otherwise, the singletons will not be
                        # singletons (will be at least two instances, one per container
                        provider = provider(self.container)
                    else:
                        provider = providers.Container(provider)
                    setattr(self.container, class_type, provider)

            if hasattr(bundle, 'wire_modules'):
                wire_modules += bundle.wire_modules

        # Applauncher services
        self.container.event_manager = providers.Object(self.event_manager)
        self.container.kernel = providers.Object(self)

        if wire_modules:
            self.console.log(f"[bold cyan]Wiring[/] modules: {wire_modules}")
            self.container.wire(modules=[
                importlib.import_module(module) for module in wire_modules
            ])
        self.console.log("Dependency container [bold]built[/]")

    def register_services(self):
        """Register the bundles services but not run them yet, it will be done later"""
        self.console.log("Registering services")
        for bundle in self.bundles:
            if hasattr(bundle, 'services'):
                for service_name, service_function, args, kwargs in bundle.services:
                    self.console.log(f"Adding {service_name}")
                    self.service_runner.add_service(name=service_name,
                                                    function=service_function,
                                                    args=args,
                                                    kwargs=kwargs)

    def __init__(self,
                 environment,
                 bundles,
                 configuration_file="config/config.yml",
                 parameters_file="config/parameters.yml"):
        self.console = Console()
        self.console.log(f"Running environment [bold green]{environment}[/]")
        self.bundles = bundles
        self.environment = environment
        self.event_manager = EventManager()
        self.service_runner = ProcessServiceRunner()
        self.shutting_down = False

        # Signals
        signal.signal(signal.SIGINT, self._signal_handler)
        signal.signal(signal.SIGTERM, self._signal_handler)

        with self.console.status("[bold green]Booting kernel..."):
            self.load_configuration(configuration_file=configuration_file,
                                    parameters_file=parameters_file)
            self.register_event_listeners(config_only=True)
            self.event_manager.dispatch(
                ConfigurationReadyEvent(configuration=self.config))
            self.register_event_listeners()
            self.build_dependency_container()
            self.event_manager.dispatch(KernelReadyEvent())
            self.register_services()

        self.service_runner.run()

    def _signal_handler(self, _os_signal, _frame):
        self.shutdown()

    def shutdown(self):
        """Start the kernel shutdown process. It will stopp all services and the exit"""
        is_main = current_process().name == 'MainProcess'
        if not self.shutting_down:
            if is_main:
                table = Table(show_header=False, style="bold red")
                table.add_row(
                    "Shutdown signal received, press ctrl + c to kill the process"
                )
                self.console.print(table)
                self.shutting_down = True
                self.service_runner.shutdown()
            # The container should be shutted down even in forks
            self.container.shutdown_resources()
        elif is_main:
            self.console.log("[bold red]Killing...[/]")
            self.service_runner.kill()

    def wait(self):
        """Wait until all services are done"""
        self.service_runner.wait()

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        self.event_manager.dispatch(KernelShutdownEvent())
Exemple #29
0
"""Dynamic container simple example."""

import dependency_injector.containers as containers
import dependency_injector.providers as providers

# Defining dynamic container:
container = containers.DynamicContainer()
container.factory1 = providers.Factory(object)
container.factory2 = providers.Factory(object)

# Creating some objects:
object1 = container.factory1()
object2 = container.factory2()

# Making some asserts:
assert object1 is not object2
assert isinstance(object1, object) and isinstance(object2, object)
Exemple #30
0
from typing import Dict

from dependency_injector import containers, providers

# Test 1: to check setattr
container1 = containers.DynamicContainer()
container1.abc = providers.Provider()

# Test 2: to check override()
container2 = containers.DynamicContainer()
container2.override(containers.DynamicContainer())

# Test 3: to check override_providers()
container3 = containers.DynamicContainer()
container3.override_providers(a=providers.Provider())

# Test 4: to check set_providers()
container4 = containers.DynamicContainer()
container4.set_providers(a=providers.Provider())

# Test 5: to check .dependencies attribute
container5 = containers.DynamicContainer()
dependencies: Dict[str, providers.Provider] = container5.dependencies

# Test 6: to check base class
container6: containers.Container = containers.DynamicContainer()