Exemple #1
0
def _scan_target(scanner: Scanner, target: Scannable):
    """ Helper to import a target if it is a string, then scan """

    if target is not None:
        if isinstance(target, str):
            target = import_module(target)
        scanner.scan(target)
Exemple #2
0
 def scan(self, module, onerror=None, ignore=None):
     """Scan the given module object for L{Method}s and register them."""
     from venusian import Scanner
     scanner = Scanner(registry=self)
     kwargs = {"onerror": onerror, "categories": ["method"]}
     if ignore is not None:
         # Only pass it if specified, for backward compatibility
         kwargs["ignore"] = ignore
     scanner.scan(module, **kwargs)
Exemple #3
0
 def scan(self, module, onerror=None, ignore=None):
     """Scan the given module object for L{Method}s and register them."""
     from venusian import Scanner
     scanner = Scanner(registry=self)
     kwargs = {"onerror": onerror, "categories": ["method"]}
     if ignore is not None:
         # Only pass it if specified, for backward compatibility
         kwargs["ignore"] = ignore
     scanner.scan(module, **kwargs)
Exemple #4
0
 def scan(self, package=None, categories=('ramverk',), **parameters):
     """Scan a module or (recursively) a package and configure the
     application using the callbacks attached to top-level objects."""
     scanner = Scanner(application=self, **parameters)
     if package is None:
         package = self.module
     if isinstance(package, basestring):
         package = import_string(package)
     scanner.scan(package, categories)
    def scan_commands(self):
        """
        Scan and register all CLI commands.

        """
        import sandglass.time.commands

        # TODO: Implement support for commands in other applications
        scanner = Scanner()
        scanner.scan(sandglass.time.commands)
def app():
    # Do this once at startup
    registry = ServiceRegistry()
    scanner = Scanner(registry=registry)
    # Point the scanner at a package/module and scan
    scanner.scan(decorators.decorator_with_wired_factory)

    # Do this for every "request" or operation
    container = registry.create_container()
    greeting: Greeting = container.get(Greeting)
    assert 'Hello from Marie' == greeting.greet()
Exemple #7
0
def test():
    # The app
    registry = ServiceRegistry()
    scanner = Scanner(registry=registry)
    scanner.scan(factories)

    # Per "request"
    container = registry.create_container()
    view: View = container.get(View)
    result = view.name
    expected = 'View - My Site'

    return expected, result
Exemple #8
0
def app():
    # Do this once at startup
    registry = ServiceRegistry()
    scanner = Scanner(registry=registry)
    # Point the scanner at a package/module and scan
    scanner.scan(decorators.basic_class)

    registry.register_factory(greeter_factory, Greeter)
    # No longer need this line
    # registry.register_factory(Greeting, Greeting)

    # Do this for every "request" or operation
    container = registry.create_container()
    greeting: Greeting = container.get(Greeting)
    assert 'Hello from Marie' == greeting.greet()
def pre_process_cli_to_discover_rules(argv=None):
    # type: (typing.Optional[typing.Sequence[typing.Text]]) -> None
    scanner = Scanner()
    rule_discovery_parser = argparse.ArgumentParser(add_help=False)
    add_rule_discovery_argument(rule_discovery_parser)
    rule_discovery_args, _ = rule_discovery_parser.parse_known_args(argv)
    for packages in (rule_discovery_args.packages_to_discover_rules_from
                     or []):
        for package in packages:
            try:
                scanner.scan(import_module(package))
            except ImportError:
                warnings.warn(
                    RuntimeWarning(
                        '\'{}\' module, specified via the rule discovery CLI, is not found. Ignoring it.'
                        .format(package)), )
Exemple #10
0
    def __post_init__(self):
        # Put some site-wide singletons into the registry, so you
        # can get them there instead of always needing this app instance
        self.scanner = Scanner(registry=self.registry)

        self.registry.register_singleton(self, ThemesterApp)
        self.registry.register_singleton(self.scanner, Scanner)
        if self.themester_config:
            self.registry.register_singleton(self.themester_config,
                                             ThemesterConfig)
            self.registry.register_singleton(
                self.themester_config.theme_config, ThemeConfig)

        # Register some factories and singletons
        self.scanner.scan(url)
        root = self.themester_config.root
        self.registry.register_singleton(root, Root)
Exemple #11
0
def app():
    # Do this once at startup
    registry = ServiceRegistry()
    scanner = Scanner(registry=registry)
    # Point the scanner at a package/module and scan
    scanner.scan(decorators.decorator_args)

    # First request, for a regular Customer
    customer1 = Customer()
    container1 = registry.create_container(context=customer1)
    greeting1: Greeting = container1.get(Greeting)
    assert 'Hello from Susan to Jill' == greeting1.greet()

    # Second request, for a FrenchCustomer
    customer2 = FrenchCustomer()
    container2 = registry.create_container(context=customer2)
    greeting2: Greeting = container2.get(Greeting)
    assert 'Hello from Marie to Juliette' == greeting2.greet()
Exemple #12
0
def wired_setup(
        registry: ServiceRegistry,
        scanner: Scanner,
):
    scanner.scan(components)
    scanner.scan(cssfiles)
    scanner.scan(sidebars)
    scanner.scan(views)
Exemple #13
0
def make_registry(
    root: Optional[Root] = None,
    root_factory: Optional[Callable] = None,
    scannables: Union[Iterable[Scannable], Scannable] = tuple(),
    plugins: Union[Iterable[Plugin], Plugin] = tuple(),
    theme_config: Optional[ThemeConfig] = None,
) -> ServiceRegistry:
    """ Construct a Themester registry with some defaults """

    registry = ServiceRegistry()

    # Handle the venusian scanner
    scanner = Scanner(registry=registry)
    registry.register_singleton(scanner, Scanner)

    # Handle the root
    if root is not None:
        registry.register_singleton(root, Root)

    # Handle a root factory
    if root_factory is not None:
        registry.register_factory(root_factory, Root)

    # Handle the theme config
    if theme_config is not None:
        registry.register_singleton(theme_config, ThemeConfig)

    # Scan themester factories
    _scan_target(scanner, factories)

    # Handle anything that needs to be scanned
    if isinstance(scannables, Sequence):
        for scannable in scannables:
            _scan_target(scanner, scannable)
    else:
        _scan_target(scanner, scannables)

    # Handle any plugins
    if isinstance(plugins, Sequence):
        for plugin in plugins:
            _setup_target(registry, scanner, plugin)
    else:
        _setup_target(registry, scanner, plugins)

    return registry
Exemple #14
0
 def _makeOne(self, **kw):
     from venusian import Scanner
     return Scanner(**kw)
Exemple #15
0
from venusian import Scanner

from app.bot import commands

commands_mapping = {}


def telegram_command(command: str):
    """
    Decorator which registers telegram command handlers
    :param command: The command from which user message should be started to be routed to this handler,including slash
                    e.g. "/start" or "/login"
    """
    def decorator(fn):
        commands_mapping[command] = fn
        return fn

    return decorator


Scanner().scan(commands)
pass
Exemple #16
0
 def load_clients(self):
     """
     Load all clients from the "clients" directory
     """
     scanner = Scanner(bot=self)
     scanner.scan(clients, categories=['cloudbot.client'])
Exemple #17
0
def wired_setup(
    registry: ServiceRegistry,
    scanner: Scanner,
):
    registry.register_factory(resource_factory, Resource)
    scanner.scan(themester.sphinx)
Exemple #18
0
def wired_setup(
    registry: ServiceRegistry,
    scanner: Scanner,
):
    scanner.scan(views)
Exemple #19
0
def wired_setup(
    registry: ServiceRegistry,
    scanner: Scanner,
):
    # Scan manually instead
    scanner.scan(import_module(Heading2.__module__))
Exemple #20
0
class InjectorRegistry(ServiceRegistry):
    """ A registry with a venusian Scanner and injector"""

    scanner: Scanner

    def __init__(self, factory_registry=None):
        super().__init__(factory_registry=factory_registry)
        self.scanner = Scanner(registry=self)

    def scan(self, pkg: PACKAGE = None):
        if pkg is None:
            # Get the caller module and import it
            pkg = caller_package()
        elif isinstance(pkg, str):
            # importlib.resource package specification
            pkg = import_module(pkg)
        self.scanner.scan(pkg)

    def create_container(self, *, context=None) -> InjectorContainer:
        return InjectorContainer(self._factories, context=context)

    def create_injectable_container(
        self, *, context=None
    ) -> InjectorContainer:
        container = self.create_container(context=context)
        injector = Injector(container)
        container.register_singleton(injector, Injector)
        return container

    def register_injectable(
        self,
        for_: Callable,
        target: Callable = None,
        context: Optional[Any] = None,
        use_props: bool = False,
    ):
        """Imperative form of the injectable decorator.

        This can be called imperatively instead of using the
        ``@injectable`` decorator. In fact, the decorator just
        calls this function.

        Args:
            for_: The type or interface to register for
            target: A callable or class to register
            context: A container context
            use_props: This factory should be injected with keyword args
        """

        def injectable_factory(container: ServiceContainer):
            if use_props:
                # Just return the target, it will be
                # constructed when the props are available
                return target
            else:
                injector = container.get(Injector)
                instance = injector(target)
                return instance

        target.__wired_factory__ = injectable_factory  # type: ignore
        self.register_factory(target, for_, context=context)
Exemple #21
0
 def __init__(self, factory_registry=None):
     super().__init__(factory_registry=factory_registry)
     self.scanner = Scanner(registry=self)
Exemple #22
0
 def scan(self, module, onerror=None):
     """Scan the given module object for L{Method}s and register them."""
     from venusian import Scanner
     scanner = Scanner(registry=self)
     scanner.scan(module, onerror=onerror, categories=["method"])
Exemple #23
0
class ThemesterApp:
    themester_config: Optional[ThemesterConfig] = None
    registry: ServiceRegistry = field(default_factory=ServiceRegistry)
    scanner: Scanner = field(init=False)

    def __post_init__(self):
        # Put some site-wide singletons into the registry, so you
        # can get them there instead of always needing this app instance
        self.scanner = Scanner(registry=self.registry)

        self.registry.register_singleton(self, ThemesterApp)
        self.registry.register_singleton(self.scanner, Scanner)
        if self.themester_config:
            self.registry.register_singleton(self.themester_config,
                                             ThemesterConfig)
            self.registry.register_singleton(
                self.themester_config.theme_config, ThemeConfig)

        # Register some factories and singletons
        self.scanner.scan(url)
        root = self.themester_config.root
        self.registry.register_singleton(root, Root)

    def setup_plugins(self):
        # Stop doing this as part of __post_init__ to let the
        # system have a chance to register things before handing to
        # plugins.

        # Now setup any configured Themester plugins
        for plugin_string in self.themester_config.plugins:
            plugin_module = import_module(plugin_string)
            self.setup_plugin(plugin_module)

    def setup_plugin(self, module):
        """ Call a plugin's setup function """

        s = getattr(module, 'wired_setup')
        s(self.registry, self.scanner)

    def render(
        self,
        container: Optional[ServiceContainer] = None,
        resource: Optional[Union[Resource, Any]] = None,
        view_name: Optional[str] = None,
    ) -> str:
        """ Render a vdom via a view from a container """

        # If a container was passed in, use it as the basis for a render
        # container. Otherwise, use the site container and bind to it.
        if container:
            this_container = container
        else:
            this_container = self.registry.create_container(context=resource)
            # If we were passed a resource, register it as a singleton in
            # the container.
            if resource is not None:
                this_container.register_singleton(resource, Resource)

        # Sometimes we want to use named views
        if view_name:
            this_view = this_container.get(View, name=view_name)
        else:
            this_view = this_container.get(View)

        # Now render a vdom
        this_vdom = this_view()
        return render(this_vdom, container=this_container)
Exemple #24
0
 def scan(self, module, onerror=None):
     """Scan the given module object for L{Method}s and register them."""
     from venusian import Scanner
     scanner = Scanner(registry=self)
     scanner.scan(module, onerror=onerror, categories=["method"])
Exemple #25
0
 def scan(self):
     # Look for decorators
     scanner = Scanner(registry=self.registry)
     scanner.scan(models)