def test_multibind() -> None:
    class Handler(ABC):
        pass

    class Handler1(Handler):
        pass

    class Handler2(Handler):
        pass

    class Handler3(Handler):
        def __init__(self, something: str):
            self.something = something

    Handlers = SequenceKey('handlers')
    Something = Key('something')

    def configure(binder: Binder) -> None:
        binder.multibind(Handlers, [Handler1()], scope=singleton)
        binder.multibind(Handlers, [Handler2()], scope=singleton)
        binder.bind(Something, 'hello', scope=singleton)

    class OmgModule(Module):
        @singleton
        @provider
        def handler3(self, something: Something) -> Handlers:
            return [Handler3(cast(str, something))]

    injector = Injector([configure, OmgModule])
    handlers = injector.get(Handlers)
    assert isinstance(handlers[0], Handler1)
    assert isinstance(handlers[1], Handler2)
    assert isinstance(handlers[2], Handler3)
    assert handlers[2].something == 'hello'
Exemple #2
0
def test_provider_sequence_decorator():
    Names = SequenceKey('names')

    class MyModule(Module):
        @provider
        def bob(self) -> Names:
            return ['Bob']

        @provider
        def tom(self) -> Names:
            return ['Tom']

    assert Injector(MyModule()).get(Names) == ['Bob', 'Tom']
Exemple #3
0
from __future__ import absolute_import

from datetime import timedelta

from injector import Injector, Module, Scope, ScopeDecorator, InstanceProvider, \
    Key, Binder, SequenceKey, MappingKey, provides, inject, singleton
from clastic import Application, Middleware as WebMiddleware, Request, render_basic
from clastic.middleware.session import CookieSessionMiddleware, JSONCookie
from werkzeug.local import Local, LocalManager

from waffle.flags import Flag, Flags
from waffle.util import parse_reltime


Routes = SequenceKey('Routes')
Middlewares = SequenceKey('Middlewares')
Resources = MappingKey('Resources')
ErrorHandlers = MappingKey('ErrorHandlers')
RenderFactory = Key('RenderFactory')
SessionCookie = JSONCookie


_routes = []


class RoutesModule(Module):
    """Bind a set of manually defined routes."""

    def __init__(self, routes):
        self._routes = routes or []
Exemple #4
0
UUID = NewType("UUID", str)
HTML = NewType("HTML", str)
ContentType = NewType("ContentType", str)
Timestamp = NewType("Timestamp", str)
# HTTPResponse = NewType("HTTPResponse", str)
T = TypeVar('T')


class HTTPResponse(Generic[T]):
    pass


Interface = NewType("Interface", object)
Implementation = NewType("Implementation", object)
Model = NewType("Model", object)

from injector import Key, MappingKey, SequenceKey

API = Key("API")
APISpec = Key("APISpec")
App = Key("App")
Apps = MappingKey("Apps")
CommandLine = Key("CommandLine")
Config = Key("Config")
Defaults = Key("Defaults")
Environment = Key("Environment")
FlaskApp = Key("FlaskApp")
OIDC = Key("OIDC")
SQLAlchemy = Key("SQLAlchemy")
SQLAlchemyBase = SequenceKey("SQLAlchemyBase")
Exemple #5
0
from argparse import ArgumentParser, HelpFormatter, SUPPRESS, OPTIONAL, ZERO_OR_MORE
from injector import Injector, Binder, Module, Key, SequenceKey, MappingKey, singleton, provides, inject


"""A configuration system backed by flags and files.

- Basically a thin wrapper around argh.
- Provides a "Flag" property for use in modules that adds global flags.
- Provides a global parser which any package can add arguments to (via the "flag" function).
- Binds parsed flags (as Flags) and individual flags (as FlagKey('flag')) to the
  injector.
- Also provides several decorators for bootstrapping an application with flags.
"""


AppStartup = SequenceKey('AppStartup')
# Parsed command line arguments can be injected with this key, or individually with FlagKey(name)
Flags = Key('Flags')
_ProvidedFlags = SequenceKey('_ProvidedFlags')
FlagDefaults = MappingKey('FlagDefaults')


class ArgumentDefaultsHelpFormatter(HelpFormatter):
    def _get_help_string(self, action):
        help = action.help
        if '%(default)' not in action.help:
            if action.default is not SUPPRESS and action.default not in (True, False):
                defaulting_nargs = [OPTIONAL, ZERO_OR_MORE]
                if action.option_strings or action.nargs in defaulting_nargs:
                    if help.endswith('.'):
                        help = help[:-1]
Exemple #6
0
from sqlalchemy.engine import Engine as DatabaseEngine
from sqlalchemy.orm import Query, sessionmaker, class_mapper
from sqlalchemy.ext.declarative import declarative_base, declared_attr
from sqlalchemy import create_engine
from sqlalchemy.exc import InvalidRequestError, IntegrityError
from sqlalchemy.orm.exc import UnmappedClassError
from sqlalchemy.orm.session import Session
from sqlalchemy.util import ThreadLocalRegistry
from sqlalchemy.sql.expression import ClauseElement

from waffle.flags import Flag

logger = logging.getLogger(__name__)

DatabaseSession = Session
DatabaseCreated = SequenceKey('DatabaseCreated')


class Query(Query):
    def flatten(self):
        """Flatten row tuples to the first (and only) value."""
        return [i for i, in self]

    def column(self, i):
        """Return list of values from column i in result."""
        return [r[i] for r in self]


class ExplicitSession(Session):
    def __init__(self, *args, **kwargs):
        super(ExplicitSession, self).__init__(*args, **kwargs)