Ejemplo n.º 1
0
def sample_interactions(registry: ServiceRegistry) -> List[str]:
    """ Pretend to do a couple of customer interactions """

    greetings = []

    bootstrap_container: ServiceContainer = registry.create_container()
    datastore: Datastore = bootstrap_container.get(Datastore)
    for customer in datastore.customers:
        # Do a sample "interaction" (aka transaction, aka request) for
        # each customer. This is like handling a view for a request.
        interaction_container = registry.create_container()
        greeting = customer_interaction(interaction_container, customer)
        greetings.append(greeting)

    return greetings
Ejemplo n.º 2
0
def setup(registry: ServiceRegistry, settings: Settings):
    # The French greeter, using context of FrenchCustomer
    punctuation = settings.punctuation

    def french_greeter_factory(container) -> Greeter:
        return FrenchGreeter(punctuation=punctuation)

    # Register it as a factory using its class for the "key", but
    # this time register with a "context"
    registry.register_factory(
        french_greeter_factory, Greeter, context=FrenchCustomer
    )

    # *** OVERRIDE !!! This add-on replaces the core, built-in Greeter
    # with a different implementation.
    def override_greeter_factory(container) -> Greeter:
        return OverrideGreeter(punctuation=punctuation)

    # Register it as a factory using its class for the "key", but
    # this time register with a "context"
    registry.register_factory(
        override_greeter_factory, Greeter, context=Customer
    )

    # Grab the Datastore and add a FrenchCustomer
    container: ServiceContainer = registry.create_container()
    datastore: Datastore = container.get(Datastore)
    customer1 = FrenchCustomer(name='Henri')
    datastore.customers.append(customer1)
Ejemplo n.º 3
0
def test():
    assert isinstance(Foo.impl00, AutowireField)
    assert isinstance(Foo.impl01, AutowireField)
    assert isinstance(Foo.impl02, AutowireField)
    assert isinstance(Foo.impl03, AutowireField)

    registry = ServiceRegistry()
    enable_autowire(registry)

    impl00 = object()
    impl01 = object()
    impl02 = object()
    impl03 = object()

    registry.register_singleton(impl00, Iface00)
    registry.register_singleton(impl01, name="impl01")
    registry.register_singleton(impl02, name="r_impl02")
    registry.register_singleton(impl03, context=Ctxt)
    registry.register_autowire(
        Foo,
        IFoo,
        namespace=dict(n_impl02="r_impl02", n_impl03=Ctxt()),
        lazy=False,
    )

    container = registry.create_container()
    foo = container.get(IFoo)
    assert foo.impl00 is impl00
    assert foo.impl01 is impl01
    assert foo.impl02 is impl02
    assert foo.impl03 is impl03
Ejemplo n.º 4
0
def render_view(
        registry: ServiceRegistry,
        view: Optional[View] = None,  # Might be in the registry already
        context: Optional[Any] = None,
        resource: Optional[Resource] = None,
        singletons: Singletons = tuple(),
) -> str:
    """ Find/render view with optional context/resource

    Any needed components must be registered before passing in registry.
    """

    if view is not None:
        if context is not None:
            register_view(registry, view, context=context.__class__)
        else:
            register_view(registry, view)
    container = registry.create_container(context=context)

    for service, iface in singletons:
        container.register_singleton(service, iface)

    if resource is not None:
        container.register_singleton(resource, Resource)

    vdom = container.get(View)
    result = render(vdom, container=container)
    return result
Ejemplo n.º 5
0
def test_component_register_component(
    registry: ServiceRegistry,
    simple_root,
):
    from wired_components.component import IComponent, register_component

    # Register a component
    @implementer(IComponent)
    @dataclass
    class SomeComponent:
        flag: int

    register_component(registry, SomeComponent)

    # Make a container with an IResource in it
    container = registry.create_container(context=simple_root)

    # Now get the component *class*
    component_class = container.get(IComponent, name='SomeComponent')

    # Try to make a component *instance*
    with pytest.raises(TypeError):
        # Requires a prop to be passed in
        component_class()

    # Now construct the component instance the correct way, with a prop
    component_instance: SomeComponent = component_class(flag=44)
    assert component_instance.flag == 44
Ejemplo n.º 6
0
def app_bootstrap(settings: Settings) -> ServiceRegistry:
    # Make the registry
    registry = ServiceRegistry()

    # Store the settings in the registry so things later can
    # get to them.
    registry.register_singleton(settings, Settings)

    # Scan for registrations
    scanner = venusian.Scanner(registry=registry, settings=settings)
    from . import models

    scanner.scan(models)

    # Grab the datastore singleton to pass into setup
    container: ServiceContainer = registry.create_container()
    datastore: Datastore = container.get(Datastore)

    # Do setup for the core application features
    setup(registry, datastore)

    # Import the add-on and initialize it
    from . import custom

    scanner.scan(custom)
    custom.setup(registry, datastore)

    return registry
Ejemplo n.º 7
0
def test_setup_target_module():
    registry = ServiceRegistry()
    dummy_scanner = DummyScanner()
    scanner = cast(Scanner, dummy_scanner)
    from themester.testing import utils_plugin1
    result = _setup_target(registry, scanner, utils_plugin1)
    container = registry.create_container()
    result1 = container.get(utils_plugin1.Heading1)
    assert utils_plugin1.Heading1 is result1
Ejemplo n.º 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.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()
Ejemplo n.º 9
0
def app():
    # Do this once at startup
    registry = ServiceRegistry()
    registry.register_factory(greeter_factory, Greeter)
    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()
Ejemplo n.º 10
0
def view_container(
    registry: ServiceRegistry,
    root_setup,
    simple_root,
    request_setup,
    configuration_setup,
) -> ServiceContainer:
    # Make a container and return it
    container: ServiceContainer = registry.create_container(
        context=simple_root['d1'])
    return container
Ejemplo n.º 11
0
def render_path(registry: ServiceRegistry, resource_path: str) -> str:
    """ Render a resource at a path, to a string """

    # Get the root, then the context at the path
    container1: ServiceContainer = registry.create_container()
    root: Root = container1.get(IRoot)
    context: Resource = find_resource(root, resource_path)

    # Now make a container to process this context
    container2: ServiceContainer = registry.create_container(context=context)
    view: View = container2.get(IView)

    renderer: JinjaRenderer = container2.get(IJinjaRenderer)
    context_dict = as_dict(view)
    template_name = view.template
    markup: Markup = renderer.render(context_dict,
                                     template_name=template_name,
                                     container=container2)

    return str(markup)
Ejemplo n.º 12
0
def greet_a_customer(registry: ServiceRegistry) -> str:
    # A customer comes in, handle the steps in the greeting
    # as a container.
    container = registry.create_container()

    # First step in the interaction: get the greeter
    the_greeter: Greeter = container.get(Greeter)

    # Now do the steps in the interaction
    greeting = the_greeter()
    return greeting
Ejemplo n.º 13
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_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()
Ejemplo n.º 14
0
def greet_customer(registry: ServiceRegistry, customer: Customer) -> str:
    # A customer comes in, handle the steps in the greeting
    # as a container.
    container = registry.create_container()

    # Get a Greeter using the customer as context. Use the Customer when
    # generating the greeting.
    greeter: Greeter = container.get(Greeter, context=customer)
    greeting = greeter(customer)

    return greeting
Ejemplo n.º 15
0
def test():
    registry = ServiceRegistry()
    registry.register_factory(view_factory, View)

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

    return expected, result
Ejemplo n.º 16
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
Ejemplo n.º 17
0
def wired_setup(registry: ServiceRegistry):
    # Wire up the normal parts of wired_components
    global_setup(registry)

    # Wire up configuration and root
    configuration_setup(registry)
    root_setup(registry)

    # Get the scanner and look for things
    container = registry.create_container()
    scanner: WiredScanner = container.get(IScanner)
    scanner.scan(components)
    scanner.scan(views)
Ejemplo n.º 18
0
class App:
    def __init__(self):
        self.registry = ServiceRegistry()
        scanner = venusian.Scanner(registry=self.registry)
        scanner.scan(models)

    def __enter__(self):
        self.container = self.registry.create_container()
        return self.container

    def __exit__(self, exc_type, exc_val, exc_tb):
        if self.container:
            del self.container
Ejemplo n.º 19
0
class _RegistrarBase:
    """Represents the base class for classes able to register and manage
    services and function as an IoC object.

    This is an internal class and not meant for directy use in code. It
    was provided as a base class to aid unit testing.
    """
    def __init__(self):
        self._registry = ServiceRegistry()

    @property
    def services(self):
        key = '_container'
        if not hasattr(self, key):
            container = self._registry.create_container()
            setattr(self, key, container)
        return getattr(self, key)

    def register_service(self,
                         service,
                         iface=Interface,
                         context=None,
                         name=''):
        service_factory = SingletonServiceWrapper(service)
        self.register_service_factory(service_factory,
                                      iface,
                                      context=context,
                                      name=name)

    def register_service_factory(self,
                                 service_factory,
                                 iface=Interface,
                                 context=None,
                                 name=''):
        self._registry.register_factory(ProxyFactory(service_factory),
                                        iface,
                                        context=context,
                                        name=name)

    def find_service_factory(self, iface, context=None, name=''):
        factory = self._registry.find_factory(iface,
                                              context=context,
                                              name=name)
        if not factory:
            raise LookupError('could not find registered service')
        if isinstance(factory, ProxyFactory):
            return factory.factory
        return factory

    def find_service(self, iface, context=None, name=''):
        return self.services.get(iface, context=context, name=name)
Ejemplo n.º 20
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()
Ejemplo n.º 21
0
def process_request(registry: ServiceRegistry, url: str) -> str:
    """ Given URL (customer name), make a Request to handle interaction """

    # Make the container that this request gets processed in
    container = registry.create_container()

    # Put the url into the container
    container.register_singleton(url, Url)

    # Create a View to generate the greeting
    view = container.get(View)

    # Generate a response
    response = view()

    return response
Ejemplo n.º 22
0
def render_vdom(
        registry: ServiceRegistry,
        vdom: VDOM,
        context: Optional[Any] = None,
        resource: Optional[Resource] = None,
        singletons: Singletons = tuple(),
) -> str:
    """ Render a VDOM to string with optional context/resource """

    container = registry.create_container(context=context)
    for service, iface in singletons:
        container.register_singleton(service, iface)

    if resource is not None:
        container.register_singleton(resource, Resource)
    result = render(vdom, container=container)
    return result
Ejemplo n.º 23
0
def assert_lazy(cls_args, cls_kwargs):
    assert isinstance(Foo.impl00, AutowireField)
    assert isinstance(Foo.impl01, AutowireField)
    assert isinstance(Foo.impl02, AutowireField)
    assert isinstance(Foo.impl03, AutowireField)
    assert isinstance(Foo.impl04, AutowireField)
    assert isinstance(Foo.impl05, AutowireField)
    assert isinstance(Foo.impl06, AutowireField)

    registry = ServiceRegistry()
    enable_autowire(registry)

    impl00 = object()
    impl01 = object()
    impl02 = object()
    impl03 = object()
    impl04 = object()
    impl05 = object()
    impl06 = object()

    registry.register_singleton(impl00, Iface00)
    registry.register_singleton(impl01, name="impl01")
    registry.register_singleton(impl02, name="r_impl02")
    registry.register_singleton(impl03, context=Ctxt)
    registry.register_singleton(impl04, name="pv_impl04")
    registry.register_singleton(impl05, context=Ctxt2)
    registry.register_singleton(impl06, context=IFoo)
    registry.register_autowire(
        Foo,
        IFoo,
        namespace=dict(n_impl02="r_impl02", n_impl03=Ctxt()),
        cls_args=cls_args,
        cls_kwargs=cls_kwargs,
        lazy=True,
    )

    container = registry.create_container()
    foo = container.get(IFoo)
    assert foo.impl00 is impl00
    assert foo.impl01 is impl01
    assert foo.impl02 is impl02
    assert foo.impl03 is impl03
    assert foo.impl04 is impl04
    assert foo.impl05 is impl05
    assert foo.impl06 is impl06
Ejemplo n.º 24
0
def setup(registry: ServiceRegistry, settings: Settings):
    # The French greeter, using context of FrenchCustomer
    punctuation = settings.punctuation

    def french_greeter_factory(container) -> Greeter:
        return FrenchGreeter(punctuation=punctuation)

    # Register it as a factory using its class for the "key", but
    # this time register with a "context"
    registry.register_factory(french_greeter_factory,
                              Greeter,
                              context=FrenchCustomer)

    # Grab the Datastore and add a FrenchCustomer
    container: ServiceContainer = registry.create_container()
    datastore: Datastore = container.get(Datastore)
    henri = FrenchCustomer(name='henri', title='Henri')
    datastore.customers['henri'] = henri
Ejemplo n.º 25
0
def render_component(
        registry: ServiceRegistry,
        component: Component,
        context: Optional[Any] = None,
        resource: Optional[Resource] = None,
        singletons: Singletons = tuple(),
) -> str:
    """ Render a component to string with optional context/resource """

    register_component(registry, component)
    container = registry.create_container(context=context)
    for service, iface in singletons:
        container.register_singleton(service, iface)

    if resource is not None:
        container.register_singleton(resource, Resource)
    vdom = html('<{component} />')
    result = render(vdom, container=container)
    return result
Ejemplo n.º 26
0
def process_request(registry: ServiceRegistry, url_value: str) -> str:
    """ Given URL (customer name), make a Request to handle interaction """

    from .models import Resource, View, Url

    # Make the container that this request gets processed in
    container = registry.create_container()

    # Put the url into the container
    url = Url(value=url_value)
    container.register_singleton(url, Url)

    # Get the context
    context = container.get(Resource)

    # Create a View to generate the greeting
    view = container.get(View, context=context)

    # Generate a response
    response = view()

    return response
Ejemplo n.º 27
0
def render_template(
        registry: ServiceRegistry,
        template: VDOM,
        context: Optional[Any] = None,
        resource: Optional[Resource] = None,
        singletons: Singletons = tuple(),
) -> str:
    """ Find/render template string with optional context/resource

    Any needed components must be registered before passing in registry.
    """

    container = registry.create_container(context=context)

    for service, iface in singletons:
        container.register_singleton(service, iface)

    if resource is not None:
        container.register_singleton(resource, Resource)

    result = render(template, container=container)
    return result
Ejemplo n.º 28
0
def test_component_register_component2(
    registry: ServiceRegistry,
    simple_root,
):
    from wired_components.component import IComponent
    from wired_components.component.register_component import register_component2

    # Register a component
    @implementer(IComponent)
    @dataclass
    class SomeComponent:
        flag: int

    register_component2(registry, SomeComponent)

    # Make a container with an IResource in it
    container = registry.create_container(context=simple_root)

    # Now get the component *class*
    component_class = container.get(IComponent, name='SomeComponent')

    # Now construct the component instance the correct way, with a prop
    component_instance: SomeComponent = component_class(flag=44)
    assert component_instance.flag == 44
Ejemplo n.º 29
0
def container():
    registry = ServiceRegistry()
    container = registry.create_container()
    return container