Exemplo n.º 1
0
    def string_or_bool(self, value):
        try:
            lowervalue = value.lower()
        except AttributeError:
            return asbool(value)

        if lowervalue in ('false', 'no', 'off', 'n', 'f', '0', 'true', 'yes',
                          'on', 'y', 't', '1'):
            return asbool(value)

        return value
Exemplo n.º 2
0
    def _add_middleware(self, conf, app):
        errorware = conf['tg.slowreqs']
        if errorware.get('enable') and not asbool(conf.get('debug')):
            reporters = []

            if errorware.get('error_email'):
                from backlash.tracing.reporters.mail import EmailReporter
                reporters.append(EmailReporter(**errorware))

            if errorware.get('sentry_dsn'):
                from backlash.tracing.reporters.sentry import SentryReporter
                reporters.append(SentryReporter(**errorware))

            if errorware.get('reporters', []):
                for reporter in errorware['reporters']:
                    reporters.append(reporter)

            try:
                import backlash
            except ImportError:  # pragma: no cover
                log.warning("backlash not installed, slow requests reporting won't be available")
            else:
                return backlash.TraceSlowRequestsMiddleware(
                    app, reporters, interval=errorware.get('interval', 25),
                    exclude_paths=errorware.get('exclude', None),
                    context_injectors=[_turbogears_backlash_context]
                )

        return app
Exemplo n.º 3
0
def ErrorReporter(app, global_conf, **errorware):

    if not asbool(global_conf.get('debug')):

        reporters = []

        if errorware.get('error_email'):
            from backlash.tracing.reporters.mail import EmailReporter
            reporters.append(EmailReporter(**errorware))

        if errorware.get('sentry_dsn'):
            from backlash.tracing.reporters.sentry import SentryReporter
            reporters.append(SentryReporter(**errorware))

        try:
            import backlash
        except ImportError:  #pragma: no cover
            log.warning('backlash not installed,'
                        ' email tracebacks won\'t be available')
        else:
            app = backlash.TraceErrorsMiddleware(
                app,
                reporters,
                context_injectors=[_turbogears_backlash_context])

    return app
Exemplo n.º 4
0
def SlowReqsReporter(app, global_conf, **errorware):

    if errorware.get('enable') and not asbool(global_conf.get('debug')):

        reporters = []

        if errorware.get('error_email'):
            from backlash.tracing.reporters.mail import EmailReporter
            reporters.append(EmailReporter(**errorware))

        if errorware.get('sentry_dsn'):
            from backlash.tracing.reporters.sentry import SentryReporter
            reporters.append(SentryReporter(**errorware))

        try:
            import backlash
        except ImportError:  #pragma: no cover
            log.warning('backlash not installed,'
                        ' slow requests reporting won\'t be available')
        else:
            app = backlash.TraceSlowRequestsMiddleware(
                app,
                reporters,
                interval=errorware.get('interval', 25),
                exclude_paths=errorware.get('exclude', None),
                context_injectors=[_turbogears_backlash_context])

    return app
Exemplo n.º 5
0
    def _add_middleware(self, conf, app):
        errorware = conf['tg.slowreqs']
        if errorware.get('enable') and not asbool(conf.get('debug')):
            reporters = []

            if errorware.get('error_email'):
                from backlash.tracing.reporters.mail import EmailReporter
                reporters.append(EmailReporter(**errorware))

            if errorware.get('sentry_dsn'):
                from backlash.tracing.reporters.sentry import SentryReporter
                reporters.append(SentryReporter(**errorware))

            if errorware.get('reporters', []):
                for reporter in errorware['reporters']:
                    reporters.append(reporter)

            try:
                import backlash
            except ImportError:  # pragma: no cover
                log.warning(
                    "backlash not installed, slow requests reporting won't be available"
                )
            else:
                return backlash.TraceSlowRequestsMiddleware(
                    app,
                    reporters,
                    interval=errorware.get('interval', 25),
                    exclude_paths=errorware.get('exclude', None),
                    context_injectors=[_turbogears_backlash_context])

        return app
Exemplo n.º 6
0
    def from_settings(cls, settings, prefix='mail.'):
        """Create a new instance of 'Mailer' from settings dict.

        :param settings: a settings dict-like
        :param prefix: prefix separating 'tgext.mailer' settings
        """
        settings = settings or {}

        kwarg_names = [
            prefix + k for k in ('host', 'port', 'username', 'password', 'tls',
                                 'ssl', 'keyfile', 'certfile', 'queue_path',
                                 'debug', 'default_sender')
        ]

        size = len(prefix)

        kwargs = dict(((k[size:], settings[k]) for k in settings.keys()
                       if k in kwarg_names))

        for key in ('tls', 'ssl'):
            val = kwargs.get(key)
            if val:
                kwargs[key] = asbool(val)

        return cls(**kwargs)
Exemplo n.º 7
0
def ErrorHandler(app, global_conf, **errorware):
    """ErrorHandler Toggle

    If debug is enabled, this function will return the app wrapped in
    the WebError ``EvalException`` middleware which displays
    interactive debugging sessions when a traceback occurs.

    Otherwise, the app will be wrapped in the WebError
    ``ErrorMiddleware``, and the ``errorware`` dict will be passed into
    it. The ``ErrorMiddleware`` handles sending an email to the address
    listed in the .ini file, under ``email_to``.

    """

    if asbool(global_conf.get('debug')):

        try:
            import backlash
        except ImportError:  #pragma: no cover
            log.warning('backlash not installed,'
                        ' debug mode won\'t be available')
        else:
            app = backlash.DebuggedApplication(
                app, context_injectors=[_turbogears_backlash_context])

    return app
Exemplo n.º 8
0
def ErrorReporter(app, global_conf, **errorware):

    if not asbool(global_conf.get('debug')):

        reporters = []

        if errorware.get('error_email'):
            from backlash.tracing.reporters.mail import EmailReporter
            reporters.append(EmailReporter(**errorware))

        if errorware.get('sentry_dsn'):
            from backlash.tracing.reporters.sentry import SentryReporter
            reporters.append(SentryReporter(**errorware))

        try:
            import backlash
        except ImportError:  #pragma: no cover
            log.warning('backlash not installed,'
                        ' email tracebacks won\'t be available')
        else:
            app = backlash.TraceErrorsMiddleware(
                app, reporters,
                context_injectors=[_turbogears_backlash_context])

    return app
Exemplo n.º 9
0
    def _add_middleware(self, conf, app):
        errorware = conf['tg.errorware']
        if errorware.get('enable', True) and not asbool(conf.get('debug')):
            reporters = []

            if errorware.get('error_email'):
                from backlash.tracing.reporters.mail import EmailReporter
                reporters.append(EmailReporter(**errorware))

            if errorware.get('sentry_dsn'):
                from backlash.tracing.reporters.sentry import SentryReporter
                reporters.append(SentryReporter(**errorware))

            if errorware.get('reporters', []):
                for reporter in errorware['reporters']:
                    reporters.append(reporter)

            try:
                import backlash
            except ImportError:  # pragma: no cover
                log.warning("backlash not installed, email tracebacks won't be available")
            else:
                return backlash.TraceErrorsMiddleware(
                    app, reporters, context_injectors=[_turbogears_backlash_context]
                )
        return app
Exemplo n.º 10
0
def SlowReqsReporter(app, global_conf, **errorware):

    if errorware.get('enable') and not asbool(global_conf.get('debug')):

        reporters = []

        if errorware.get('error_email'):
            from backlash.tracing.reporters.mail import EmailReporter
            reporters.append(EmailReporter(**errorware))

        if errorware.get('sentry_dsn'):
            from backlash.tracing.reporters.sentry import SentryReporter
            reporters.append(SentryReporter(**errorware))

        try:
            import backlash
        except ImportError:  #pragma: no cover
            log.warning('backlash not installed,'
                        ' slow requests reporting won\'t be available')
        else:
            app = backlash.TraceSlowRequestsMiddleware(
                app, reporters, interval=errorware.get('interval', 25),
                exclude_paths=errorware.get('exclude', None),
                context_injectors=[_turbogears_backlash_context])

    return app
Exemplo n.º 11
0
def ErrorHandler(app, global_conf, **errorware):
    """ErrorHandler Toggle

    If debug is enabled, this function will return the app wrapped in
    the WebError ``EvalException`` middleware which displays
    interactive debugging sessions when a traceback occurs.

    Otherwise, the app will be wrapped in the WebError
    ``ErrorMiddleware``, and the ``errorware`` dict will be passed into
    it. The ``ErrorMiddleware`` handles sending an email to the address
    listed in the .ini file, under ``email_to``.

    """

    if asbool(global_conf.get('debug')):

        try:
            import backlash
        except ImportError:  #pragma: no cover
            log.warning('backlash not installed,'
                        ' debug mode won\'t be available')
        else:
            app = backlash.DebuggedApplication(
                app, context_injectors=[_turbogears_backlash_context])

    return app
Exemplo n.º 12
0
    def _add_middleware(self, conf, app):
        errorware = conf['tg.errorware']
        if errorware.get('enable', True) and not asbool(conf.get('debug')):
            reporters = []

            if errorware.get('error_email'):
                from backlash.tracing.reporters.mail import EmailReporter
                reporters.append(EmailReporter(**errorware))

            if errorware.get('sentry_dsn'):
                from backlash.tracing.reporters.sentry import SentryReporter
                reporters.append(SentryReporter(**errorware))

            if errorware.get('reporters', []):
                for reporter in errorware['reporters']:
                    reporters.append(reporter)

            try:
                import backlash
            except ImportError:  # pragma: no cover
                log.warning(
                    "backlash not installed, email tracebacks won't be available"
                )
            else:
                return backlash.TraceErrorsMiddleware(
                    app,
                    reporters,
                    context_injectors=[_turbogears_backlash_context])
        return app
Exemplo n.º 13
0
def ErrorReporter(app, global_conf, **errorware):
    """Provides Error reporting through Backlash on TurboGears.

    This is enabled/disabled through the ``debug`` configuration option.
    Currently EMail and Sentry backlash reporters can be enabled.

    All the options available for error reporting are configured
    as ``trace_errors.*`` options in your ``app_cfg`` or ``.ini`` files.

    The available options for **EMail** reporter are:

        - ``trace_errors.enable`` -> Enable or disable error reporting,
          by default is enabled if backlash is available and ``debug=false``
        - ``trace_errors.smtp_server`` -> SMTP Server to connect to for sending emails
        - ``trace_errors.smtp_port`` -> SMTP port to connect to
        - ``trace_errors.from_address`` -> Address sending the error emails
        - ``trace_errors.error_email`` -> Address the error emails should be sent to.
        - ``trace_errors.smtp_username`` -> Username to authenticate on SMTP server.
        - ``trace_errors.smtp_password`` -> Password to authenticate on SMTP server.
        - ``trace_errors.smtp_use_tls`` -> Whenever to enable or not TLS for SMTP.
        - ``trace_errors.error_subject_prefix`` -> Prefix to append to error emails,
          by default ``WebApp Error:`` is prepended.
        - ``trace_errors.dump_request`` -> Whenever to attach a request dump to the email so that
          all request data is provided.
        - ``trace_errors.dump_request_size`` -> Do not dump request if it's bigger than this value,
          useful for uploaded files. By default 50K.
        - ``trace_errors.dump_local_frames`` -> Enable dumping local variables in case of crashes.
        - ``trace_errors.dump_local_frames_count`` -> Dump up to X frames when dumping local variables.
          The default is 2

    Available options for **Sentry** reporter are:

        - ``trace_errors.sentry_dsn`` -> Sentry instance where to send the errors.

    """

    if errorware.get('enable', True) and not asbool(global_conf.get('debug')):

        reporters = []

        if errorware.get('error_email'):
            from backlash.tracing.reporters.mail import EmailReporter
            reporters.append(EmailReporter(**errorware))

        if errorware.get('sentry_dsn'):
            from backlash.tracing.reporters.sentry import SentryReporter
            reporters.append(SentryReporter(**errorware))

        try:
            import backlash
        except ImportError:  #pragma: no cover
            log.warning('backlash not installed,'
                        ' email tracebacks won\'t be available')
        else:
            app = backlash.TraceErrorsMiddleware(
                app, reporters,
                context_injectors=[_turbogears_backlash_context])

    return app
Exemplo n.º 14
0
def ErrorReporter(app, global_conf, **errorware):
    """Provides Error reporting through Backlash on TurboGears.

    This is enabled/disabled through the ``debug`` configuration option.
    Currently EMail and Sentry backlash reporters can be enabled.

    All the options available for error reporting are configured
    as ``trace_errors.*`` options in your ``app_cfg`` or ``.ini`` files.

    The available options for **EMail** reporter are:

        - ``trace_errors.smtp_server`` -> SMTP Server to connect to for sending emails
        - ``trace_errors.from_address`` -> Address sending the error emails
        - ``trace_errors.error_email`` -> Address the error emails should be sent to.
        - ``trace_errors.smtp_username`` -> Username to authenticate on SMTP server.
        - ``trace_errors.smtp_password`` -> Password to authenticate on SMTP server.
        - ``trace_errors.smtp_use_tls`` -> Whenever to enable or not TLS for SMTP.
        - ``trace_errors.error_subject_prefix`` -> Prefix to append to error emails,
          by default ``WebApp Error:`` is prepended.
        - ``trace_errors.dump_request`` -> Whenever to attach a request dump to the email so that
          all request data is provided.
        - ``trace_errors.dump_request_size`` -> Do not dump request if it's bigger than this value,
          useful for uploaded files. By default 50K.
        - ``trace_errors.dump_local_frames`` -> Enable dumping local variables in case of crashes.
        - ``trace_errors.dump_local_frames_count`` -> Dump up to X frames when dumping local variables.
          The default is 2

    Available options for **Sentry** reporter are:

        - ``trace_errors.sentry_dsn`` -> Sentry instance where to send the errors.

    """

    if not asbool(global_conf.get('debug')):

        reporters = []

        if errorware.get('error_email'):
            from backlash.tracing.reporters.mail import EmailReporter
            reporters.append(EmailReporter(**errorware))

        if errorware.get('sentry_dsn'):
            from backlash.tracing.reporters.sentry import SentryReporter
            reporters.append(SentryReporter(**errorware))

        try:
            import backlash
        except ImportError:  #pragma: no cover
            log.warning('backlash not installed,'
                        ' email tracebacks won\'t be available')
        else:
            app = backlash.TraceErrorsMiddleware(
                app, reporters,
                context_injectors=[_turbogears_backlash_context])

    return app
Exemplo n.º 15
0
 def _add_middleware(self, conf, app):
     if asbool(conf.get('debug')):
         try:
             import backlash
         except ImportError:  # pragma: no cover
             log.warning("backlash not installed, debug mode won't be available")
         else:
             return backlash.DebuggedApplication(
                 app, context_injectors=[_turbogears_backlash_context]
             )
     return app
Exemplo n.º 16
0
 def _add_middleware(self, conf, app):
     if asbool(conf.get('debug')):
         try:
             import backlash
         except ImportError:  # pragma: no cover
             log.warning(
                 "backlash not installed, debug mode won't be available")
         else:
             return backlash.DebuggedApplication(
                 app, context_injectors=[_turbogears_backlash_context])
     return app
Exemplo n.º 17
0
 def test_asbool_truthy(self):
     assert asbool('true')
     assert asbool('yes')
     assert asbool('on')
     assert asbool('y')
     assert asbool('t')
     assert asbool('1')
Exemplo n.º 18
0
 def test_asbool_falsy(self):
     assert not asbool('false')
     assert not asbool('no')
     assert not asbool('off')
     assert not asbool('n')
     assert not asbool('f')
     assert not asbool('0')
Exemplo n.º 19
0
 def test_asbool_falsy(self):
     assert not asbool('false')
     assert not asbool('no')
     assert not asbool('off')
     assert not asbool('n')
     assert not asbool('f')
     assert not asbool('0')
Exemplo n.º 20
0
 def test_asbool_truthy(self):
     assert asbool('true')
     assert asbool('yes')
     assert asbool('on')
     assert asbool('y')
     assert asbool('t')
     assert asbool('1')
Exemplo n.º 21
0
    def create(cls, config, app_globals):
        """Setup a renderer and loader for Genshi templates.

        Override this to customize the way that the internationalization
        filter, template loader

        """
        if genshi is None:  # pragma: no cover
            # Genshi not available
            return None

        # Patch for Genshi on Python3.4
        if asbool(config.get('templating.genshi.name_constant_patch', False)):
            from genshi.template.astutil import ASTCodeGenerator
            if not hasattr(ASTCodeGenerator, 'visit_NameConstant'):

                def _visit_NameConstant(self, node):
                    if node.value is None:
                        self._write('None')
                    elif node.value is True:
                        self._write('True')
                    elif node.value is False:
                        self._write('False')
                    else:
                        raise Exception("Unknown NameConstant %r" %
                                        (node.value, ))

                ASTCodeGenerator.visit_NameConstant = _visit_NameConstant

        if config.get('use_dotted_templatenames', True):
            TemplateLoader = DottedTemplateLoader
            template_loader_args = {
                'dotted_finder': app_globals.dotted_filename_finder
            }
        else:
            TemplateLoader = GenshiTemplateLoader
            template_loader_args = {}

        loader = TemplateLoader(search_path=config.paths.templates,
                                max_cache_size=asint(
                                    config.get('genshi.max_cache_size', 30)),
                                auto_reload=config.auto_reload_templates,
                                callback=cls.on_template_loaded,
                                **template_loader_args)

        return {'genshi': cls(loader, config)}
Exemplo n.º 22
0
def SlowReqsReporter(app, global_conf, **errorware):
    """Provides slow requests reporting for TurboGears through BackLash.

    This is enabled through the ``trace_slowreqs.enable`` option and
    is only enabled when ``debug=false``.

    All the options available for error reporting are configured
    as ``trace_slowreqs.*`` options in your ``app_cfg`` or ``.ini`` files:

        - ``trace_slowreqs.enable`` -> Enable/Disable slow requests reporting
        - ``trace_slowreqs.interval`` -> Report requests slower than this value (default: 25s)
        - ``trace_slowreqs.exclude`` -> List of urls that should be excluded

    Slow requests are reported using *EMail* or *Sentry*, the same
    options available in :class:`.ErrorReporter` apply with ``trace_slowreqs.``
    instead of ``trace_errors.``.

    """
    if errorware.get('enable') and not asbool(global_conf.get('debug')):

        reporters = []

        if errorware.get('error_email'):
            from backlash.tracing.reporters.mail import EmailReporter
            reporters.append(EmailReporter(**errorware))

        if errorware.get('sentry_dsn'):
            from backlash.tracing.reporters.sentry import SentryReporter
            reporters.append(SentryReporter(**errorware))

        try:
            import backlash
        except ImportError:  #pragma: no cover
            log.warning('backlash not installed,'
                        ' slow requests reporting won\'t be available')
        else:
            app = backlash.TraceSlowRequestsMiddleware(
                app,
                reporters,
                interval=errorware.get('interval', 25),
                exclude_paths=errorware.get('exclude', None),
                context_injectors=[_turbogears_backlash_context])

    return app
Exemplo n.º 23
0
def setup_application(app):
    config = app.config

    # we want our low level middleware to get to the request ASAP. We don't
    # need any stack middleware in them - especially no StatusCodeRedirect buffering
    app = SimpleHg(app, config)
    app = SimpleGit(app, config)

    # Enable https redirects based on HTTP_X_URL_SCHEME set by proxy
    if any(asbool(config.get(x)) for x in ['https_fixup', 'force_https', 'use_htsts']):
        app = HttpsFixup(app, config)

    app = PermanentRepoUrl(app, config)

    # Optional and undocumented wrapper - gives more verbose request/response logging, but has a slight overhead
    if str2bool(config.get('use_wsgi_wrapper')):
        app = RequestWrapper(app, config)

    return app
Exemplo n.º 24
0
def SlowReqsReporter(app, global_conf, **errorware):
    """Provides slow requests reporting for TurboGears through BackLash.

    This is enabled through the ``trace_slowreqs.enable`` option and
    is only enabled when ``debug=false``.

    All the options available for error reporting are configured
    as ``trace_slowreqs.*`` options in your ``app_cfg`` or ``.ini`` files:

        - ``trace_slowreqs.enable`` -> Enable/Disable slow requests reporting
        - ``trace_slowreqs.interval`` -> Report requests slower than this value (default: 25s)
        - ``trace_slowreqs.exclude`` -> List of urls that should be excluded

    Slow requests are reported using *EMail* or *Sentry*, the same
    options available in :class:`.ErrorReporter` apply with ``trace_slowreqs.``
    instead of ``trace_errors.``.

    """
    if errorware.get('enable') and not asbool(global_conf.get('debug')):

        reporters = []

        if errorware.get('error_email'):
            from backlash.tracing.reporters.mail import EmailReporter
            reporters.append(EmailReporter(**errorware))

        if errorware.get('sentry_dsn'):
            from backlash.tracing.reporters.sentry import SentryReporter
            reporters.append(SentryReporter(**errorware))

        try:
            import backlash
        except ImportError:  #pragma: no cover
            log.warning('backlash not installed,'
                        ' slow requests reporting won\'t be available')
        else:
            app = backlash.TraceSlowRequestsMiddleware(
                app, reporters, interval=errorware.get('interval', 25),
                exclude_paths=errorware.get('exclude', None),
                context_injectors=[_turbogears_backlash_context])

    return app
Exemplo n.º 25
0
    def create(cls, config, app_globals):
        """Setup a renderer and loader for Genshi templates.

        Override this to customize the way that the internationalization
        filter, template loader

        """
        if genshi is None:  # pragma: no cover
            # Genshi not available
            return None

        # Patch for Genshi on Python3.4
        if asbool(config.get('templating.genshi.name_constant_patch', False)):
            from genshi.template.astutil import ASTCodeGenerator
            if not hasattr(ASTCodeGenerator, 'visit_NameConstant'):
                def _visit_NameConstant(self, node):
                    if node.value is None:
                        self._write('None')
                    elif node.value is True:
                        self._write('True')
                    elif node.value is False:
                        self._write('False')
                    else:
                        raise Exception("Unknown NameConstant %r" % (node.value,))
                ASTCodeGenerator.visit_NameConstant = _visit_NameConstant

        if config.get('use_dotted_templatenames', True):
            TemplateLoader = DottedTemplateLoader
            template_loader_args = {'dotted_finder': app_globals.dotted_filename_finder}
        else:
            TemplateLoader = GenshiTemplateLoader
            template_loader_args = {}

        loader = TemplateLoader(search_path=config.paths.templates,
                                max_cache_size=asint(config.get('genshi.max_cache_size', 30)),
                                auto_reload=config.auto_reload_templates,
                                callback=cls.on_template_loaded,
                                **template_loader_args)

        return {'genshi': cls(loader, config)}
Exemplo n.º 26
0
    def __call__(self, app):
        try:
            # If specified on plugtime, force the specified one
            # useful for tests or scripts.
            using_debugmailer = self.options['debugmailer']
        except KeyError:
            # Otherwise use the option provided in configuration file.
            using_debugmailer = config.get('mail.debugmailer', False)

        if using_debugmailer == 'dummy':
            mailer_factory = self._create_dummy_mailer
        elif asbool(using_debugmailer):
            mailer_factory = self._create_debug_mailer
        else:
            mailer_factory = self._create_standard_mailer

        config['tg.app_globals']._mailer_factory = mailer_factory

        global_mailer = mailer_factory(config)
        config['tg.app_globals']._mailer = global_mailer

        log.info('Configured %s', global_mailer.__class__.__name__)
        return app
Exemplo n.º 27
0
    def __call__(self, app):
        try:
            # If specified on plugtime, force the specified one
            # useful for tests or scripts.
            using_debugmailer = self.options['debugmailer']
        except KeyError:
            # Otherwise use the option provided in configuration file.
            using_debugmailer = config.get('mail.debugmailer', False)

        if using_debugmailer == 'dummy':
            mailer_factory = self._create_dummy_mailer
        elif asbool(using_debugmailer):
            mailer_factory = self._create_debug_mailer
        else:
            mailer_factory = self._create_standard_mailer

        config['tg.app_globals']._mailer_factory = mailer_factory

        global_mailer = mailer_factory(config)
        config['tg.app_globals']._mailer = global_mailer

        log.info('Configured %s', global_mailer.__class__.__name__)
        return app
Exemplo n.º 28
0
    def wrapper(func, *args, **kwargs):
        """Decorator wrapper"""
        tg_locals = tg.request.environ['tg.locals']
        enabled = tg_locals.config.get("cache_enabled", "True")

        if not asbool(enabled):
            return func(*args, **kwargs)

        if key:
            key_dict = kwargs.copy()
            key_dict.update(_make_dict_from_args(func, args))
            if query_args:
                key_dict.update(tg_locals.request.GET.mixed())

            if key != "cache_default":
                if isinstance(key, list):
                    key_dict = dict((k, key_dict[k]) for k in key)
                else:
                    key_dict = {key: key_dict[key]}
        else:
            key_dict = None

        self = None
        if args:
            self = args[0]
        namespace, cache_key = create_cache_key(func, key_dict, self)

        if type:
            b_kwargs['type'] = type

        cache_obj = getattr(tg_locals, 'cache', None)
        if not cache_obj: # pragma: no cover
            raise Exception('No CacheMiddleware or cache object on '
                            ' app_globals was found')

        my_cache = cache_obj.get_cache(namespace, **b_kwargs)

        if expire == "never":
            cache_expire = None
        else:
            cache_expire = expire

        def create_func():
            result = func(*args, **kwargs)
            glob_response = tg_locals.response
            headers = glob_response.headerlist
            status = glob_response.status
            full_response = dict(headers=headers, status=status,
                                 cookies=None, content=result)
            return full_response

        response = my_cache.get_value(cache_key, createfunc=create_func,
                                      expiretime=cache_expire,
                                      starttime=starttime)
        if cache_response:
            glob_response = tg_locals.response
            glob_response.headerlist = [header for header in response['headers']
                                        if header[0].lower() in cache_headers]
            glob_response.status = response['status']

        return response['content']
Exemplo n.º 29
0
def setup_auth(app,
               authmetadata,
               form_plugin=None,
               form_identifies=True,
               cookie_secret='secret',
               cookie_name='authtkt',
               login_url='/login',
               login_handler='/login_handler',
               post_login_url=None,
               logout_handler='/logout_handler',
               post_logout_url=None,
               login_counter_name=None,
               cookie_timeout=None,
               cookie_reissue_time=None,
               **who_args):
    """
    Sets :mod:`repoze.who` up with the provided authenticators and
    options to create FriendlyFormPlugin/FastFormPlugin.

    It returns a middleware that provides identification,
    authentication and authorization in a way that is compatible
    with repoze.who and repoze.what.
    """
    if 'charset' in who_args:  #pragma: no cover
        log.warn('charset argument in authentication setup is ignored')
        who_args.pop('charset')

    # If no identifiers are provided in repoze setup arguments
    # then create a default one using AuthTktCookiePlugin.
    if 'identifiers' not in who_args:
        from repoze.who.plugins.auth_tkt import AuthTktCookiePlugin
        cookie = AuthTktCookiePlugin(cookie_secret,
                                     cookie_name,
                                     timeout=cookie_timeout,
                                     reissue_time=cookie_reissue_time)
        who_args['identifiers'] = [('cookie', cookie)]
        who_args['authenticators'].insert(0, ('cookie', cookie))

    # If no form plugin is provided then create a default
    # one using the provided options.
    if form_plugin is None:
        from tg.configuration.auth.fastform import FastFormPlugin
        form = FastFormPlugin(login_url,
                              login_handler,
                              post_login_url,
                              logout_handler,
                              post_logout_url,
                              rememberer_name='cookie',
                              login_counter_name=login_counter_name)
    else:
        form = form_plugin

    if form_identifies:
        who_args['identifiers'].insert(0, ('main_identifier', form))

    # Setting the repoze.who challengers:
    if 'challengers' not in who_args:
        who_args['challengers'] = []
    who_args['challengers'].append(('form', form))

    # Including logging
    log_file = who_args.pop('log_file', None)
    if log_file is not None:
        if log_file.lower() == 'stdout':
            log_stream = sys.stdout
        elif log_file.lower() == 'stderr':
            log_stream = sys.stderr
        else:
            log_stream = open(log_file, 'wb')
        who_args['log_stream'] = log_stream

    log_level = who_args.get('log_level', None)
    if log_level is None:
        log_level = logging.INFO
    else:
        log_level = _LEVELS[log_level.lower()]
    who_args['log_level'] = log_level

    # Setting up the metadata provider for the user informations
    if 'mdproviders' not in who_args:
        who_args['mdproviders'] = []

    if authmetadata:
        authmd = _AuthMetadataProvider(authmetadata)
        who_args['mdproviders'].append(('authmd', authmd))

    # Set up default classifier
    if 'classifier' not in who_args:
        who_args['classifier'] = default_request_classifier

    # Set up default challenger decider
    if 'challenge_decider' not in who_args:
        who_args['challenge_decider'] = turbogears_challenge_decider

    skip_authn = who_args.pop('skip_authentication', False)
    if asbool(skip_authn):
        return _AuthenticationForgerMiddleware(app, **who_args)
    else:
        return PluggableAuthenticationMiddleware(app, **who_args)
Exemplo n.º 30
0
def _cached_call(func,
                 args,
                 kwargs,
                 namespace,
                 cache_key,
                 expire="never",
                 type=None,
                 starttime=None,
                 cache_headers=('content-type', 'content-length'),
                 cache_response=True,
                 cache_extra_args=None):
    """
    Optional arguments:

    ``key_func``
        Function used to genereate the cache key, the function name
        and class will be used as the base for the cache key. If None
        the ``func`` itself will be used. It's usually handy when
        creating caches for decorated functions, for which we want the
        cache key to be generated on the decorated function and not on
        the decorator.
    ``key_dict``
        Arguments used to generate the cache key, only the arguments
        listed into this dictionary will be used to generate the
        cache key together with the key_func.
    ``expire``
        Time in seconds before cache expires, or the string "never".
        Defaults to "never"
    ``type``
        Type of cache to use: dbm, memory, file, memcached, or None for
        Beaker's default
    ``cache_headers``
        A tuple of header names indicating response headers that
        will also be cached.
    ``invalidate_on_startup``
        If True, the cache will be invalidated each time the application
        starts or is restarted.
    ``cache_response``
        Determines whether the response at the time beaker_cache is used
        should be cached or not, defaults to True.

        .. note::
            When cache_response is set to False, the cache_headers
            argument is ignored as none of the response is cached.

    If cache.enabled is set to False in the .ini file, then cache is
    disabled globally.
    """

    tg_locals = tg.request.environ['tg.locals']
    enabled = asbool(tg_locals.config.get("cache.enabled", True))

    if not enabled:
        return func(*args, **kwargs)

    cache_extra_args = cache_extra_args or {}

    if type:
        cache_extra_args['type'] = type

    cache_obj = getattr(tg_locals, 'cache', None)
    if not cache_obj:  # pragma: no cover
        raise Exception(
            'TurboGears Cache object not found, ensure cache.enabled=True')

    my_cache = cache_obj.get_cache(namespace, **cache_extra_args)

    if expire == "never":
        cache_expire = None
    else:
        cache_expire = expire

    def create_func():
        result = func(*args, **kwargs)
        glob_response = tg_locals.response
        headers = glob_response.headerlist
        status = glob_response.status
        full_response = dict(headers=headers,
                             status=status,
                             cookies=None,
                             content=result)
        return full_response

    response = my_cache.get_value(cache_key,
                                  createfunc=create_func,
                                  expiretime=cache_expire,
                                  starttime=starttime)
    if cache_response:
        glob_response = tg_locals.response
        glob_response.headerlist = [
            header for header in response['headers']
            if header[0].lower() in cache_headers
        ]
        glob_response.status = response['status']

    return response['content']
Exemplo n.º 31
0
 def test_asbool_broken(self):
     asbool('Test')
Exemplo n.º 32
0
def _cached_call(func, args, kwargs, key_func, key_dict,
                 expire="never", type=None, starttime=None,
                 cache_headers=('content-type', 'content-length'),
                 cache_response=True, cache_extra_args=None):
    """
    Optional arguments:

    ``key_func``
        Function used to genereate the cache key, the function name
        and class will be used as the base for the cache key. If None
        the ``func`` itself will be used. It's usually handy when
        creating caches for decorated functions, for which we want the
        cache key to be generated on the decorated function and not on
        the decorator.
    ``key_dict``
        Arguments used to generate the cache key, only the arguments
        listed into this dictionary will be used to generate the
        cache key together with the key_func.
    ``expire``
        Time in seconds before cache expires, or the string "never".
        Defaults to "never"
    ``type``
        Type of cache to use: dbm, memory, file, memcached, or None for
        Beaker's default
    ``cache_headers``
        A tuple of header names indicating response headers that
        will also be cached.
    ``invalidate_on_startup``
        If True, the cache will be invalidated each time the application
        starts or is restarted.
    ``cache_response``
        Determines whether the response at the time beaker_cache is used
        should be cached or not, defaults to True.

        .. note::
            When cache_response is set to False, the cache_headers
            argument is ignored as none of the response is cached.

    If cache.enabled is set to False in the .ini file, then cache is
    disabled globally.
    """

    tg_locals = tg.request.environ['tg.locals']
    enabled = asbool(tg_locals.config.get("cache.enabled", True))

    if not enabled:
        return func(*args, **kwargs)

    cache_extra_args = cache_extra_args or {}

    self = None
    if args:
        self = args[0]
    namespace, cache_key = create_cache_key(key_func, key_dict, self)

    if type:
        cache_extra_args['type'] = type

    cache_obj = getattr(tg_locals, 'cache', None)
    if not cache_obj:  # pragma: no cover
        raise Exception('TurboGears Cache object not found, ensure cache.enabled=True')

    my_cache = cache_obj.get_cache(namespace, **cache_extra_args)

    if expire == "never":
        cache_expire = None
    else:
        cache_expire = expire

    def create_func():
        result = func(*args, **kwargs)
        glob_response = tg_locals.response
        headers = glob_response.headerlist
        status = glob_response.status
        full_response = dict(headers=headers, status=status,
                             cookies=None, content=result)
        return full_response

    response = my_cache.get_value(cache_key,
                                  createfunc=create_func,
                                  expiretime=cache_expire,
                                  starttime=starttime)
    if cache_response:
        glob_response = tg_locals.response
        glob_response.headerlist = [header for header in response['headers']
                                    if header[0].lower() in cache_headers]
        glob_response.status = response['status']

    return response['content']
Exemplo n.º 33
0
 def test_asbool_broken(self):
     asbool('Test')
Exemplo n.º 34
0
def setup_auth(app, form_plugin=None, form_identifies=True,
               cookie_secret='secret', cookie_name='authtkt',
               login_url='/login', login_handler='/login_handler',
               post_login_url=None, logout_handler='/logout_handler',
               post_logout_url=None, login_counter_name=None,
               cookie_timeout=None, cookie_reissue_time=None,
               **who_args):
    """
    Sets :mod:`repoze.who` up with the provided authenticators and
    options to create FriendlyFormPlugin/FastFormPlugin.

    It returns a middleware that provides identification,
    authentication and authorization in a way that is compatible
    with repoze.who and repoze.what.
    """
    if 'charset' in who_args: #pragma: no cover
        log.warn('charset argument in authentication setup is ignored')
        who_args.pop('charset')

    # If no identifiers are provided in repoze setup arguments
    # then create a default one using AuthTktCookiePlugin.
    if 'identifiers' not in who_args:
        from repoze.who.plugins.auth_tkt import AuthTktCookiePlugin
        cookie = AuthTktCookiePlugin(cookie_secret, cookie_name,
                                     timeout=cookie_timeout,
                                     reissue_time=cookie_reissue_time)
        who_args['identifiers'] = [('cookie', cookie)]
        who_args['authenticators'].insert(0, ('cookie', cookie))

    # If no form plugin is provided then create a default
    # one using the provided options.
    if form_plugin is None:
        from tg.configuration.auth.fastform import FastFormPlugin
        form = FastFormPlugin(login_url, login_handler, post_login_url,
                              logout_handler, post_logout_url,
                              rememberer_name='cookie',
                              login_counter_name=login_counter_name)
    else:
        form = form_plugin

    if form_identifies:
        who_args['identifiers'].insert(0, ('main_identifier', form))

    # Setting the repoze.who challengers:
    if 'challengers' not in who_args:
        who_args['challengers'] = []
    who_args['challengers'].append(('form', form))

    # Including logging
    log_file = who_args.pop('log_file', None)
    if log_file is not None:
        if log_file.lower() == 'stdout':
            log_stream = sys.stdout
        elif log_file.lower() == 'stderr':
            log_stream = sys.stderr
        else:
            log_stream = open(log_file, 'wb')
        who_args['log_stream'] = log_stream

    log_level = who_args.get('log_level', None)
    if log_level is None:
        log_level = logging.INFO
    else:
        log_level = _LEVELS[log_level.lower()]
    who_args['log_level'] = log_level

    # Setting up the metadata provider for the user information
    if 'mdproviders' not in who_args:
        who_args['mdproviders'] = []

    # Set up default classifier
    if 'classifier' not in who_args:
        who_args['classifier'] = default_request_classifier

    # Set up default challenger decider
    if 'challenge_decider' not in who_args:
        who_args['challenge_decider'] = turbogears_challenge_decider

    skip_authn = who_args.pop('skip_authentication', False)
    if asbool(skip_authn):
        return _AuthenticationForgerMiddleware(app, **who_args)
    else:
        return PluggableAuthenticationMiddleware(app, **who_args)