Beispiel #1
0
def include(app):
    conversion_map = {
        'authenticator': 'object',
        'authorizer': 'object',
    }
    defaults = {
        'authorizer': None,
    }
    required = ('authenticator',)
    settings = parse_settings(
        app.settings, conversion_map=conversion_map, defaults=defaults,
        required=required, prefix='tangled.auth.')

    app['authenticator'] = settings['authenticator']
    app['authenticator.args'] = parse_settings(
        settings, prefix='authenticator.')

    app['authorizer'] = settings['authorizer']
    app['authorizer.args'] = parse_settings(settings, prefix='authorizer.')

    if app['authorizer'] and not app['authenticator']:
        raise ConfigurationError('No authenticator registered')

    app.settings['tangled.app.handler.auth'] = auth_handler
    app.add_config_field('*/*', 'requires_authentication', False)
    app.add_config_field('*/*', 'permission', None)
    app.add_config_field('*/*', 'not_logged_in', False)
    app.add_request_attribute(authenticator)
    app.add_request_attribute(authorizer)
def include(app):
    conversion_map = {
        'url': make_url,
        'make_engine': 'object',
        'make_session_factory': 'object',
        'sessionmaker.class_': 'object',
        'sessionmaker.autoflush': 'bool',
        'sessionmaker.autocommit': 'bool',
        'sessionmaker.expire_on_commit': 'bool',
    }
    defaults = {
        'make_engine': make_engine,
        'make_session_factory': make_session_factory,
    }
    settings = parse_settings(
        app.settings, conversion_map=conversion_map, defaults=defaults,
        prefix='sqlalchemy.')

    engine = settings['make_engine'](app, settings)
    app['sqlalchemy.engine'] = engine

    session_factory = settings['make_session_factory'](app, settings)
    app['sqlalchemy.session_factory'] = session_factory

    def make_db_session(request):
        return request.app['sqlalchemy.session_factory']()

    @cached_property
    def db_session(request):
        session = request.make_db_session()
        request.on_finished(close, session)
        return session

    def close(app, request, response, session):
        if response is None or (400 <= response.status_int < 599):
            session.rollback()
            log.debug('Session rolled back')
        else:
            session.commit()
            log.debug('Session committed')
        session.close()
        log.debug('Session closed')

    @property
    @contextlib.contextmanager
    def managed_db_session(request):
        session = request.make_db_session()
        try:
            yield session
        except:
            session.rollback()
            raise
        else:
            session.commit()
        finally:
            session.close()

    app.add_request_attribute(make_db_session)
    app.add_request_attribute(db_session)
    app.add_request_attribute(managed_db_session)
Beispiel #3
0
def make_app_settings(settings, conversion_map={}, defaults={}, required=(),
                      prefix=None, strip_prefix=True, parse=True, section='app',
                      **extra_settings):
    """Create a properly initialized application settings dict.

    In simple cases, you don't need to call this directly--you can just
    pass a settings file name or a plain dict to
    :class:`tangled.web.app.Application`, and this will be called for
    you.

    If you need to do custom parsing (e.g., if your app has custom
    settings), you can call this function with a conversion map,
    defaults, &c. It's a wrapper around :func:`.parse_settings` that
    adds a bit of extra functionality:

        - A file name can be passed instead of a settings dict, in
          which case the settings will be extracted from the specified
          ``section`` of that file.
        - Core tangled.web defaults are *always* added because
          :class:`tangled.web.app.Application` assumes they are always
          set.
        - Settings parsing can be disabled by passing ``parse=False``.
          This only applies to *your* settings, including defaults and
          extra settings (*core* defaults are always parsed).
        - Extra settings can be passed as keyword args; they will
          override all other settings, and they will be parsed (or not)
          along with other settings.
        - Required settings are checked for after all the settings are
          merged.

    In really special cases you can create a subclass of
    :class:`.AAppSettings` and then construct your settings dict by
    hand (eschewing the use of this function).

    """
    app_settings = parse_settings_file(
        'tangled.web:defaults.ini', conversion_map=CONVERSION_MAP,
        meta_settings=False)
    if isinstance(settings, str):
        settings = parse_settings_file(settings, section=section)
    settings.update(extra_settings)
    if parse:
        _conversion_map = CONVERSION_MAP.copy()
        _conversion_map.update(conversion_map)
        settings = parse_settings(
            settings, conversion_map=_conversion_map, defaults=defaults,
            prefix=prefix, strip_prefix=strip_prefix)
    else:
        app_settings.update(defaults)
    app_settings.update(settings)
    check_required(app_settings, required)
    return AppSettings(app_settings)
Beispiel #4
0
def create_lookup(settings):
    """Create Mako template lookup after application is created."""
    conversion_map = {
        'default_filters': 'list',
        'directories': as_list_of(abs_path),
        'file_system_checks': 'bool',
        'imports': 'list',
    }
    defaults = {
        'default_filters': 'h',
        'input_encoding': 'utf-8',
        'output_encoding': None,
    }
    lookup_args = parse_settings(
        settings, conversion_map=conversion_map, defaults=defaults,
        prefix='mako.lookup.')
    lookup = TemplateLookup(**lookup_args)
    return lookup
Beispiel #5
0
def create_lookup(settings):
    """Create Mako template lookup after application is created."""
    conversion_map = {
        'default_filters': 'list',
        'directories': as_list_of(abs_path),
        'file_system_checks': 'bool',
        'imports': 'list',
    }
    defaults = {
        'default_filters': 'h',
        'input_encoding': 'utf-8',
        'output_encoding': None,
    }
    lookup_args = parse_settings(settings,
                                 conversion_map=conversion_map,
                                 defaults=defaults,
                                 prefix='mako.lookup.')
    lookup = TemplateLookup(**lookup_args)
    return lookup
Beispiel #6
0
def include(app):
    conversion_map = {
        'auto': 'bool',
        # TODO: Support datetime and timedelta too?
        'cookie_expires': as_first_of('int', 'bool'),
    }
    defaults = {
        'auto': True,
        'cookie_expires': True,
        'type': 'file',
        'data_dir': os.path.join(os.getcwd(), 'data/session'),
    }
    required = ('key', 'secret')
    settings = parse_settings(
        app.settings, conversion_map=conversion_map, defaults=defaults,
        required=required, prefix='beaker.session.')
    app['session_factory'] = SessionObject
    app['session_factory.args'] = settings
    app.add_request_attribute(session)
    app.add_request_attribute(flash)