Exemple #1
0
    def _confused_state(self, request: Request) -> Type[BaseState]:
        """
        If we're confused, find which state to call.
        """

        origin = request.register.get(Register.STATE)

        if origin in self._allowed_states:
            try:
                return import_class(origin)
            except (AttributeError, ImportError):
                pass

        return import_class(settings.DEFAULT_STATE)
Exemple #2
0
def create_context_store(name='default',
                         ttl=settings.CONTEXT_DEFAULT_TTL,
                         store=settings.CONTEXT_STORE) -> 'BaseContextStore':
    """
    Create a context store. By default using the default configured context
    store, but you can use a custom class if you want to using the `store`
    setting.

    The time to live of each store (aka there is one per conversation) is
    defined by the `ttl` value, which is also inferred by default from the
    configuration.

    You can have several stores existing in parallel. To make the distinction
    between them you need to give them different names, using the `name`
    parameter.

    The usage looks like:

    >>> cs = create_context_store()
    >>> class Hello(BaseTestState):
    >>>     @cs.inject(['foo'])
    >>>     async def handle(self, context):
    >>>         logger.debug('foo is %s', context['foo'])
    >>>
    >>>     async def missing_context(self):
    >>>         self.send(lyr.Text('`foo` is not in context'))

    This requires that `foo` is present in the context in order to enter the
    handler.

    See `BaseContextStore.inject()` for more info.
    """

    store_class = import_class(store['class'])
    return store_class(name=name, ttl=ttl, **store['params'])
Exemple #3
0
    def health_check(cls):
        """
        Checks that the configuration makes sense.
        """

        try:
            assert isinstance(settings.MIDDLEWARES, list)
        except AssertionError:
            yield HealthCheckFail(
                '00005',
                'The "MIDDLEWARES" configuration key should be assigned '
                'to a list',
            )
            return

        for m in settings.MIDDLEWARES:
            try:
                c = import_class(m)
            except (TypeError, ValueError, AttributeError, ImportError):
                yield HealthCheckFail(
                    '00005',
                    f'Cannot import middleware "{m}"',
                )
            else:
                if not issubclass(c, BaseMiddleware):
                    yield HealthCheckFail(
                        '00005',
                        f'Middleware "{m}" does not implement '
                        f'"BaseMiddleware"',
                    )
Exemple #4
0
    def _make_register(self) -> BaseRegisterStore:
        """
        Make the register storage.
        """

        s = settings.REGISTER_STORE
        store_class = import_class(s['class'])
        return store_class(**s['params'])
Exemple #5
0
async def providers():
    """
    Iterates over all instances of analytics provider found in configuration
    """

    for provider in settings.ANALYTICS_PROVIDERS:
        cls: BaseAnalytics = import_class(provider['class'])
        yield await cls.instance(*provider['args'])
Exemple #6
0
    def _init_loaders(self) -> None:
        """
        This creates the loaders instances and subscribes to their updates.
        """

        for loader in settings.I18N_TRANSLATION_LOADERS:
            loader_class = import_class(loader['loader'])
            instance = loader_class()
            instance.on_update(self.update)
            run(instance.load(**loader['params']))
Exemple #7
0
    def _init_loaders(self) -> None:
        """
        Gets loaders from conf, make instances and subscribe to them.
        """

        for loader in settings.I18N_INTENTS_LOADERS:
            loader_class = import_class(loader['loader'])
            instance = loader_class()
            instance.on_update(self.update)
            run(instance.load(**loader['params']))
Exemple #8
0
    def settings(cls):
        """
        Find the settings for the current class inside the platforms
        configuration.
        """

        from bernard.platforms.management import get_platform_settings

        for platform in get_platform_settings():
            candidate = import_class(platform['class'])
            if candidate == cls:
                return platform.get('settings', {})
Exemple #9
0
    async def health_check(self) -> Iterator[HealthCheckFail]:
        """
        Perform the checks. So far:

        - Make a list of the unique destination states from the transitions
          list, then check the health of each of them.
        """

        ds_class = getattr(settings, 'DEFAULT_STATE', '')
        forbidden_defaults = [None, '', 'bernard.engine.state.DefaultState']

        if ds_class in forbidden_defaults:
            yield HealthCheckFail(
                '00005',
                f'Default state (`DEFAULT_STATE` in settings) is not set. '
                f'You need to set it to your own implementation. Please refer '
                f'yourself to the doc. See '
                f'https://github.com/BernardFW/bernard/blob/develop/doc/'
                f'get_started.md#statespy')

        try:
            import_class(ds_class)
        except (ImportError, KeyError, AttributeError, TypeError):
            yield HealthCheckFail(
                '00005', f'Cannot import "{ds_class}", which is the value'
                f' of `DEFAULT_STATE` in the configuration. This means either'
                f' that your `PYTHONPATH` is wrong or that the value you gave'
                f' to `DEFAULT_STATE` is wrong. You need to provide a default'
                f' state class for this framework to work. Please refer'
                f' yourself to the documentation for more information. See'
                f' https://github.com/BernardFW/bernard/blob/develop/doc/'
                f'get_started.md#statespy')

        states = set(t.dest for t in self.transitions)

        for state in states:
            async for check in state.health_check():
                yield check
Exemple #10
0
    def init(self):
        """
        Imports and caches all middleware classes.
        """

        self.middlewares = [import_class(c) for c in self._middlewares_classes]