Beispiel #1
0
 def __call__(self, event):
     item = event.target['item']
     instantiated = False
     raw = None
     if isinstance(item, FunctionType):
         raw = item
     elif not isinstance(item, str):
         initialized = item
         instantiated = True
     else:
         with ignored(ImportError, AttributeError):
             raw = load_definition_from_string(item)
     if not instantiated:
         if not raw:
             raise NameError(
                 'Cannot initialize dependency {0}, the module may not exist.'.format(item))
         args, kwargs = [], {}
         if isinstance(raw, FunctionType):
             kwargs['container'] = self.container
         init = event.target.get('init', {})
         if isinstance(init, dict):
             for key, val in init.items():
                 kwargs[key] = get_param_from_container(val, self.container)
         elif isinstance(init, list):
             for arg in init:
                 args.append(get_param_from_container(arg, self.container))
         initialized = raw(*args, **kwargs)
     return initialized
Beispiel #2
0
 def wrapper(self, *args, **kwargs):
     if not hasattr(self.request, "user"):
         self.request.user = None
     auth_config = self.container.get("application.config")["auth"]
     valid = True
     if self.request.user:
         # User is already authenticated, redirect to success url
         if auto_redirect:
             return self.redirect(auth_config["url"]["login_success"])
     form_config = auth_config["form"]
     if self.request.is_method(method):
         # Form has been posted, validate the user
         form_class_module = form_class or form_config["class"]
         form = imports.load_definition_from_string(form_class_module)()
         form.data = self.request
         if form.is_valid():
             authenticator = self.container.get("auth_authenticator")
             username_field = getattr(form, form_config["username"])
             password_field = getattr(form, form_config["password"])
             user = authenticator.authenticate(username=username_field.value, password=password_field.value)
             if user:
                 self.request.user = user
                 self.request.session[auth_config["session"]["key"]] = getattr(
                     user, auth_config["db"]["username_field"]
                 )
                 if auto_redirect:
                     return self.redirect(auth_config["url"]["login_success"])
             else:
                 valid = False
         else:
             valid = False
     if not valid:
         self.flash_messages.add(form_config["invalid_message"], "error")
         return self.redirect(auth_config["url"]["login"])
     return func(self, **kwargs)
    def __init__(self, config=None):
        """Initializes the application.

        Registers any events that are within the application configuration.

        Example:

        .. code-block:: python

            app = Base()

        Events:
            Dispatches the INIT.

        Args:
            config (mixed): See the Base.config properties.
        """
        Base.global_app = self
        self.config = config or {}
        if not self.config.get('exceptions'):
            self.exception_class = ApplicationError
        else:
            self.exception_class = imports.load_definition_from_string(
                self.config['exceptions']['class'])
        self.register_events()
        self.trigger_init_event()
        super(Base, self).__init__()
    def register_components(self):
        """Register any components specified with the application.

        Components can include the following modules:
            - dependencies
            - events
            - models
            - routes
            - views

        Registering a component will merge any configuration settings within
        the above modules prior to the application booting.

        An example component might look like:

        /component
            /views
                /index.html
            /routes.py
            /views.py
        """
        types = ('dependencies', 'events', 'routes', 'models', 'views')
        for component in self.config['components']:
            for type_ in types:
                with contextmanagers.suppress(Exception):
                    type_component = imports.load_definition_from_string(
                        '{}.{}.{}'.format(component, type_, type_))
                    if type_ == 'dependencies':
                        self.container.update(type_component)
                    if not isinstance(type_component, ModuleType):
                        self._config[type_] = dict_deep_update(
                            self._config.get(type_, {}), type_component)
            self._config['views'][
                'renderers']['jinja2']['config']['packages'].append(
                (component, 'views'))
Beispiel #5
0
 def wrapper(self, *args, **kwargs):
     provider = self.container.get(DEPENDENCY)
     redirect_url = provider.config.get('authenticated_route', redirect)
     if self.request.user:
         return self.redirect(redirect_url)
     form = imports.load_definition_from_string(
         form_class)(action=self.request)
     form.data = self.request
     user = None
     if self.request.is_method(method):
         if form.is_valid():
             user = provider.authenticate(
                 username=getattr(form, provider.user_model_identifier),
                 password=form.password)
         if user:
             if self.request.get['redirect']:
                 redirect_url = parse.unquote_plus(
                     self.request.get['redirect'])
             if provider.user_meets_requirements(user, requires):
                 provider.login(user, self.request)
                 if redirect_callback:
                     redirect_url = redirect_callback(user)
         else:
             self.flash_messages.add(
                 invalid_credentials_message, namespace='error')
             redirect_url = form.action
         return self.redirect(redirect_url, clear=True)
     kwargs['form'] = form
     return func(self, **kwargs)
Beispiel #6
0
    def __init__(self, config=None):
        """Initializes the application.

        Registers any events that are within the application configuration.

        Example:

        .. code-block:: python

            app = Base()

        Events:
            Dispatches the INIT.

        Args:
            config (mixed): See the Base.config properties.
        """
        Base.global_app = self
        self.config = config or {}
        if 'exceptions' not in self.config:
            self.exception_class = ApplicationError
        else:
            self.exception_class = imports.load_definition_from_string(
                self.config['exceptions']['class'])
        self.register_events()
        self.trigger_init_event()
        super(Base, self).__init__()
Beispiel #7
0
 def wrapper(self, *args, **kwargs):
     provider = self.container.get(DEPENDENCY)
     redirect_url = provider.config.get('authenticated_route', redirect)
     if self.request.user:
         return self.redirect(redirect_url)
     form = imports.load_definition_from_string(
         form_class)(action=self.request)
     if self.request.is_method(method):
         user = None
         namespace = 'error'
         message = error_message
         form.data = self.request
         if form.is_valid():
             forgotten_password_token_manager = self.container.get(
                 'auth_forgotten_password_token_manager')
             forgotten_password_token_manager.provider = provider
             email_address = getattr(form, provider.config['model']['identifier'])
             user = provider.get_user_by_email_address(email_address)
         if user:
             namespace = 'success'
             message = success_message
             token = forgotten_password_token_manager.create_token(
                 user, self.request)
             forgotten_password_token_manager.notify_user(
                 user,
                 request=self.request,
                 subject=subject,
                 template=template,
                 token=token)
         self.flash_messages.add(message, namespace)
         return self.redirect(str(self.request.url))
     kwargs['form'] = form
     return func(self, **kwargs)
Beispiel #8
0
 def _get_dependency(self, definition):
     """Loads a definition item.
     """
     item = definition['item']
     if isinstance(item, str):
         item = imports.load_definition_from_string(definition['item'])
     return item
Beispiel #9
0
 def __call__(self, event):
     item = event.target['item']
     instantiated = False
     raw = None
     if isinstance(item, FunctionType):
         raw = item
     elif not isinstance(item, str):
         initialized = item
         instantiated = True
     else:
         with ignored(ImportError, AttributeError):
             raw = load_definition_from_string(item)
     if not instantiated:
         if not raw:
             raise NameError(
                 'Cannot initialize dependency {0}, the module may not exist.'
                 .format(item))
         args, kwargs = [], {}
         if isinstance(raw, FunctionType):
             kwargs['container'] = self.container
         init = event.target.get('init', {})
         if isinstance(init, dict):
             for key, val in init.items():
                 kwargs[key] = get_param_from_container(val, self.container)
         elif isinstance(init, list):
             for arg in init:
                 args.append(get_param_from_container(arg, self.container))
         initialized = raw(*args, **kwargs)
     return initialized
Beispiel #10
0
    def runserver(self, host, port, noreload):
        """Runs the development server for the current application.

        Args:
            host: The host to bind to
            port: The port to run on
        """
        app_dir = os.environ['APP_DIR']
        app_module = os.environ['APP_MODULE']
        script_dir = os.environ['SCRIPT_DIR']
        public_dir = os.environ['PUBLIC_DIR']
        os.chdir(app_dir)
        app = load_definition_from_string('{0}.app.application'.format(
            app_module))
        kwargs = {
            'app': app,
            'script_dir': script_dir,
            'public_dir': public_dir,
        }
        if host:
            kwargs['host'] = host
        if port:
            kwargs['port'] = int(port)
        kwargs['noreload'] = True if noreload else False

        make_dev_server(**kwargs)
Beispiel #11
0
 def session(self):
     if not self._session:
         if not self._session_options:
             self._session_options = {}
         storage = load_definition_from_string(self._session_class)
         session_cookie = self.cookies[COOKIE_KEY]
         self._session = storage(id=session_cookie.value, **self._session_options) if session_cookie else storage(**self._session_options)
     return self._session
Beispiel #12
0
 def _process_config(self, config):
     if 'serializer_class' in config:
         self.serializer_class = imports.load_definition_from_string(
             config['serializer_class'])
         del config['serializer_class']
     if 'encoding' in config:
         self.encoding = config['encoding']
         del config['encoding']
Beispiel #13
0
 def _load_metadata(self, metadata):
     if isinstance(metadata, str):
         try:
             return imports.load_definition_from_string(metadata)
         except Exception as e:
             raise ConsoleError(
                 'Missing connection metadata for {} ({})'.format(
                     metadata, e))
Beispiel #14
0
 def execute(self):
     from __main__ import APP_MODULE, APP_DIR, SCRIPT_DIR, PUBLIC_DIR
     app = load_definition_from_string(
         '{0}.app.application'.format(APP_MODULE))
     os.chdir(APP_DIR)
     make_dev_server(app,
                     do_reload=True,
                     script_dir=SCRIPT_DIR,
                     public_dir=PUBLIC_DIR)
Beispiel #15
0
 def __find(self, name):
     """
     Attempts to retrieve a definition from the container configuration. If
     no definition is found, it will attempt to add the requested dependency
     to the container.
     """
     definitions = self.definitions
     if name not in definitions:
         try:
             load_definition_from_string(name)
             self.add(name, name)
             definitions = self.definitions
         except:
             raise KeyError('Dependency {} does not exist'.format(name))
     if 'item' not in definitions[name]:
         raise KeyError('item not specified in dependency definition')
     definition = definitions[name]
     definition['type'] = definition.get('type', 'singleton').lower()
     return definition
Beispiel #16
0
 def __find(self, name):
     """
     Attempts to retrieve a definition from the container configuration. If
     no definition is found, it will attempt to add the requested dependency
     to the container.
     """
     definitions = self.definitions
     if name not in definitions:
         try:
             load_definition_from_string(name)
             self.add(name, name)
             definitions = self.definitions
         except:
             raise KeyError('Dependency {} does not exist'.format(name))
     if 'item' not in definitions[name]:
         raise KeyError('item not specified in dependency definition')
     definition = definitions[name]
     definition['type'] = definition.get('type', 'singleton').lower()
     return definition
Beispiel #17
0
 def session(self):
     if not self._session:
         if not self._session_options:
             self._session_options = {}
         storage = load_definition_from_string(self._session_class)
         session_cookie = self.cookies[COOKIE_KEY]
         self._session = storage(
             id=session_cookie.value, **
             self._session_options) if session_cookie else storage(
                 **self._session_options)
     return self._session
Beispiel #18
0
    def __init__(self, config=None):
        """Initializes the container and set some default configuration options.

        Args:
            dict config: A dict containing the params, definitions and processors.
        """
        self.config = dict_deep_update(DEFAULTS, config or {})
        self.__instantiated = {}
        for event, listeners in self.config['processors'].items():
            for processor in listeners:
                self.attach_processor(event, load_definition_from_string(processor)())
Beispiel #19
0
 def session(self):
     session_class = self.environ.get('watson.session.class', None)
     if session_class and not self._session:
         storage = load_definition_from_string(session_class)
         options = self.environ['watson.session.options'].copy()
         http_cookie = self.environ.get('HTTP_COOKIE', None)
         if (http_cookie and '{0}='.format(COOKIE_KEY) in http_cookie):
             session_cookie = self.cookies[COOKIE_KEY]
             if session_cookie:
                 options['id'] = session_cookie.value
         self._session = storage(**options)
     return self._session
Beispiel #20
0
 def execute(self):
     app_dir = os.environ['APP_DIR']
     app_module = os.environ['APP_MODULE']
     script_dir = os.environ['SCRIPT_DIR']
     public_dir = os.environ['PUBLIC_DIR']
     os.chdir(app_dir)
     app = load_definition_from_string('{0}.app.application'.format(
         app_module))
     make_dev_server(app,
                     do_reload=True,
                     script_dir=script_dir,
                     public_dir=public_dir)
Beispiel #21
0
    def commands(self):
        """A list of all commands added to the runner.

        Returns:
            OrderedDict containing all the commands.
        """
        commands = {}
        for command in self._commands:
            if isinstance(command, str):
                command = load_definition_from_string(command)
            commands[command.name] = command
        return OrderedDict(sorted(commands.items()))
Beispiel #22
0
    def commands(self):
        """A list of all commands added to the runner.

        Returns:
            OrderedDict containing all the commands.
        """
        commands = {}
        for command in self._commands:
            if isinstance(command, str):
                command = load_definition_from_string(command)
            commands[command.cased_name()] = command
        return OrderedDict(sorted(commands.items()))
Beispiel #23
0
def populate(session, file_name):
    total = 0
    with open(file_name) as file:
        json_data = json.loads(file.read())
        with transaction_scope(session) as session:
            for item in json_data:
                class_ = imports.load_definition_from_string(item['class'])
                basic_fields = {k: v for k, v in item['fields'].items() if not isinstance(v, (list, tuple))}
                obj = class_(**basic_fields)
                total += 1
                session.add(obj)
    return total
Beispiel #24
0
    def __init__(self, config=None):
        """Initializes the container and set some default configuration options.

        Args:
            dict config: A dict containing the params, definitions and processors.
        """
        self.config = dict_deep_update(DEFAULTS, config or {})
        self.__instantiated = {}
        for event, listeners in self.config['processors'].items():
            for processor in listeners:
                self.attach_processor(event,
                                      load_definition_from_string(processor)())
Beispiel #25
0
 def __init__(self, config, application, renderer):
     """Application can be any WSGI callable
     """
     self.application = application
     self.config = config
     self.renderer = renderer
     self.panels = collections.OrderedDict()
     for module, settings in config['panels'].items():
         if settings['enabled']:
             panel = imports.load_definition_from_string(
                 module)(settings, renderer, application)
             panel.register_listeners()
             self.panels[module] = panel
Beispiel #26
0
 def __init__(self, config, application, renderer):
     """Application can be any WSGI callable
     """
     self.application = application
     self.config = config
     self.renderer = renderer
     self.panels = collections.OrderedDict()
     for module, settings in config['panels'].items():
         if settings['enabled']:
             panel = imports.load_definition_from_string(module)(
                 settings, renderer, application)
             panel.register_listeners()
             self.panels[module] = panel
Beispiel #27
0
    def __init__(self, config=None):
        """Initializes the container and set some default configuration options.

        Args:
            config (dict): The params, definitions and processors.
        """
        self.__instantiated__ = {}
        self.config = dict_deep_update(DEFAULTS, config or {})
        self.__instantiated__ = {}
        self._pre_process_event = types.Event(name=PRE_EVENT)
        self._post_process_event = types.Event(name=POST_EVENT)
        for event, listeners in self.config['processors'].items():
            for processor in listeners:
                self.attach_processor(
                    event,
                    imports.load_definition_from_string(processor)())
Beispiel #28
0
 def _setup_provider(self, app, provider, config_):
     auth_config = app.config['auth']
     provider_ = imports.load_definition_from_string(provider)
     provider_config = datastructures.dict_deep_update(
         auth_config['common'], provider_.defaults)
     provider_config = datastructures.dict_deep_update(
         provider_config, config_)
     config_.update(provider_config)
     dependency_config = {
         'init': {
             'config': lambda container: container.get('application.config')['auth']['providers'][provider],
             'session': lambda container: container.get('sqlalchemy_session_{0}'.format(container.get('application.config')['auth']['providers'][provider]['session'])),
         }
     }
     dependency_config.update(app.config['dependencies'][
                                 'definitions'].get(provider, {}))
     app.container.add_definition(provider, dependency_config)
Beispiel #29
0
    def create_user(self, username, password, auth_provider, database):
        """Create a new user.

        Args:
            username: The username of the user
            password: The password of the user
            database: The name of the database session.
        """
        session = ensure_session_in_container(self.container, database)
        provider = self.container.get(auth_provider)
        user_model = provider.config['model']['class']
        model_class = imports.load_definition_from_string(user_model)
        with transaction_scope(session) as session:
            user = model_class()
            setattr(user, provider.config['model']['identifier'], username)
            setattr(user, 'password', password)
            session.add(user)
            self.write('Created user {}'.format(username))
Beispiel #30
0
 def execute(self):
     app_dir = os.environ['APP_DIR']
     app_module = os.environ['APP_MODULE']
     script_dir = os.environ['SCRIPT_DIR']
     public_dir = os.environ['PUBLIC_DIR']
     os.chdir(app_dir)
     app = load_definition_from_string('{0}.app.application'.format(
         app_module))
     kwargs = {
         'app': app,
         'script_dir': script_dir,
         'public_dir': public_dir,
     }
     if self.parsed_args.host:
         kwargs['host'] = self.parsed_args.host
     if self.parsed_args.port:
         kwargs['port'] = int(self.parsed_args.port)
     make_dev_server(**kwargs)
Beispiel #31
0
 def execute(self):
     app_dir = os.environ['APP_DIR']
     app_module = os.environ['APP_MODULE']
     script_dir = os.environ['SCRIPT_DIR']
     public_dir = os.environ['PUBLIC_DIR']
     os.chdir(app_dir)
     app = load_definition_from_string(
         '{0}.app.application'.format(app_module))
     kwargs = {
         'app': app,
         'script_dir': script_dir,
         'public_dir': public_dir,
     }
     if self.parsed_args.host:
         kwargs['host'] = self.parsed_args.host
     if self.parsed_args.port:
         kwargs['port'] = int(self.parsed_args.port)
     make_dev_server(**kwargs)
Beispiel #32
0
 def wrapper(self, *args, **kwargs):
     provider = self.container.get(DEPENDENCY)
     form = imports.load_definition_from_string(
         form_class)(action=self.request)
     form.data = self.request
     user = None
     if self.request.is_method(method):
         result = {}
         if form.is_valid():
             user = provider.authenticate(
                 username=getattr(form, provider.user_model_identifier),
                 password=form.password)
         if user and provider.user_meets_requirements(user, requires):
             result['token'] = provider.login(user, self.request)
         else:
             self.response.status_code = 403
             result['message'] = 'Unable to authenticate the specified credentials.'
         return Model(format='json', data=result)
     return func(self, **kwargs)
Beispiel #33
0
 def wrapper(self, *args, **kwargs):
     provider = self.container.get(DEPENDENCY)
     redirect_url = provider.config.get('authenticated_route', redirect)
     if self.request.user:
         return self.redirect(redirect_url)
     form = imports.load_definition_from_string(
         form_class)(action=self.request)
     kwargs['form'] = form
     forgotten_password_token_manager = self.container.get(
         'auth_forgotten_password_token_manager')
     forgotten_password_token_manager.provider = provider
     token = forgotten_password_token_manager.get_token(
         self.request.get['token'])
     namespace = 'error'
     message = error_message
     if self.request.is_method(method):
         form.data = self.request
         redirect_url = str(self.request.url)
         if form.is_valid():
             if token:
                 message = success_message
                 namespace = 'success'
                 forgotten_password_token_manager.update_user_password(
                     token, form.password)
                 forgotten_password_token_manager.notify_user(
                         token.user,
                         request=self.request,
                         subject=subject,
                         template=template,
                         password=form.password)
                 if authenticate_on_reset:
                     provider.login(token.user, self.request)
         else:
             message = invalid_message
         self.flash_messages.add(message, namespace)
         return self.redirect(redirect_url, clear=True)
     if not token:
         self.flash_messages.add(message, namespace)
         return self.redirect(
             provider.config['forgotten_password_route'])
     return func(self, **kwargs)
Beispiel #34
0
 def test_load_invalid_definition(self):
     with raises(ImportError):
         imports.load_definition_from_string('invalid.module.Class')
Beispiel #35
0
 def test_from_cache(self):
     imports.load_definition_from_string('tests.watson.common.support.DATA')
     assert 'tests.watson.common.support.DATA' in imports.definition_lookup
Beispiel #36
0
 def test_load_definition_from_string(self):
     assert isinstance(
         load_definition_from_string('watson.http.MIME_TYPES'), dict)
Beispiel #37
0
 def test_load_definition_from_string(self):
     data = imports.load_definition_from_string(
         'tests.watson.common.support.DATA')
     assert isinstance(data, dict)
Beispiel #38
0
 def __call__(self, event):
     app = event.target
     config = app.config['logging']
     logger_config_callable = imports.load_definition_from_string(
         config['callable'])
     logger_config_callable(config['options'])
Beispiel #39
0
config = context.config

fileConfig(config.config_file_name)
logger = logging.getLogger('alembic.env')

watson = config.watson

USE_TWOPHASE = watson['config']['migrations']['use_twophase']

target_metadata = {}
engines = {}
for name, options in watson['config']['connections'].items():
    metadata = options['metadata']
    if isinstance(metadata, str):
        metadata = load_definition_from_string(metadata).metadata
    target_metadata[name] = metadata
    engines[name] = {
        'url': options['connection_string'],
        'instance': watson['container'].get(
            'sqlalchemy_engine_{0}'.format(name))
    }


def run_migrations_offline():
    """Run migrations in 'offline' mode.

    This configures the context with just a URL
    and not an Engine, though an Engine is acceptable
    here as well.  By skipping the Engine creation
    we don't even need a DBAPI to be available.
 def test_load_invalid_definition(self):
     with raises(ImportError):
         imports.load_definition_from_string('invalid.module.Class')
Beispiel #41
0
 def test_load_definition_from_string(self):
     assert isinstance(
         load_definition_from_string(
             'watson.http.MIME_TYPES'),
         dict)
Beispiel #42
0
 def test_load_invalid_definition(self):
     assert None == load_definition_from_string('invalid.module.Class')
Beispiel #43
0
 def test_load_invalid_definition(self):
     assert None == load_definition_from_string('invalid.module.Class')
 def test_from_cache(self):
     imports.load_definition_from_string('tests.watson.common.support.DATA')
     assert 'tests.watson.common.support.DATA' in imports.definition_lookup
Beispiel #45
0
 def __call__(self, event):
     app = event.target
     config = app.config['logging']
     logger_config_callable = imports.load_definition_from_string(
         config['callable'])
     logger_config_callable(config['options'])