Exemplo n.º 1
0
    def register(self, hook_name, func, controller=None):
        """Registers a TurboGears hook.

        Given an hook name and a function it registers the provided
        function for that role. For a complete list of hooks
        provided by default have a look at :ref:`hooks_and_events`.

        It permits to register hooks both application wide
        or for specific controllers::

            tg.hooks.register('before_render', hook_func, controller=RootController.index)
            tg.hooks.register('startup', startup_function)

        """
        if hook_name in ('startup', 'shutdown') and controller is not None:
            raise TGConfigError(
                'Startup and Shutdown hooks cannot be registered on controllers'
            )

        if hook_name == 'controller_wrapper':
            raise TGConfigError(
                'tg.hooks.wrap_controller must be used to register wrappers')

        if controller is None:
            config_ready.register(_ApplicationHookRegistration(
                hook_name, func))
        else:
            controller = default_im_func(controller)
            renderers_ready.register(
                _ControllerHookRegistration(controller, hook_name, func))
Exemplo n.º 2
0
    def lookup_controller(cls, config, controller):
        """Locates a controller by attempting to import it then grab
        the SomeController instance from the imported module.

        Override this to change how the controller object is found once
        the URL has been resolved.

        :param dict config: The configuration options for the application,
         usually this will be ``tg.config``.
        :param str controller: The controller name, this will be the name
         of the python module containing the controller.

        """
        root_module_path = config['paths']['root']
        base_controller_path = config['paths']['controllers']
        if base_controller_path is None:
            raise TGConfigError('Unable to load controllers, no controllers path configured!')

        # remove the part of the path we expect to be the root part (plus one '/')
        assert base_controller_path.startswith(root_module_path)
        controller_path = base_controller_path[len(root_module_path)+1:]

        # attach the package
        full_module_name = '.'.join([config['package_name']] +
                                    controller_path.split(os.sep) +
                                    controller.split('/'))

        # Hide the traceback here if the import fails (bad syntax and such)
        __traceback_hide__ = 'before_and_this'

        __import__(full_module_name)
        module_name = controller.split('/')[-1]
        class_name = cls.class_name_from_module_name(module_name) + 'Controller'
        return getattr(sys.modules[full_module_name], class_name)
Exemplo n.º 3
0
    def _setup_renderers(self, conf, app):
        renderers = conf['renderers']
        rendering_engines = conf['rendering_engines']

        for renderer in renderers[:]:
            if renderer in rendering_engines:
                rendering_engine = rendering_engines[renderer]
                engines = rendering_engine.create(conf, conf['tg.app_globals'])
                if engines is None:
                    log.error('Failed to initialize %s template engine, removing it...' % renderer)
                    renderers.remove(renderer)
                else:
                    log.debug('Enabling renderer %s', renderer)
                    conf['render_functions'].update(engines)
            else:
                raise TGConfigError('This configuration object does '
                                    'not support the %s renderer' % renderer)

        milestones.renderers_ready.reach()
Exemplo n.º 4
0
    def wrap_controller(self, func, controller=None):
        """Registers a TurboGears controller wrapper.

        Controller Wrappers are much like a **decorator** applied to
        every controller.
        They receive :class:`tg.configuration.AppConfig` instance
        as an argument and the next handler in chain and are expected
        to return a new handler that performs whatever it requires
        and then calls the next handler.

        A simple example for a controller wrapper is a simple logging wrapper::

            def controller_wrapper(app_config, caller):
                def call(*args, **kw):
                    try:
                        print 'Before handler!'
                        return caller(*args, **kw)
                    finally:
                        print 'After Handler!'
                return call

            tg.hooks.wrap_controller(controller_wrapper)

        It is also possible to register wrappers for a specific controller::

            tg.hooks.wrap_controller(controller_wrapper, controller=RootController.index)

        """
        if environment_loaded.reached:
            raise TGConfigError(
                'Controller wrappers can be registered only at '
                'configuration time.')

        if controller is None:
            environment_loaded.register(
                _ApplicationHookRegistration('controller_wrapper', func))
        else:
            controller = default_im_func(controller)
            registration = _ControllerHookRegistration(controller,
                                                       'controller_wrapper',
                                                       func)
            renderers_ready.register(registration)
Exemplo n.º 5
0
def auth_force_login(user_name):
    """Forces user login if authentication is enabled.

    As TurboGears identifies users by ``user_name`` the passed parameter should
    be anything your application declares being the ``user_name`` field in models.

    """
    req = request._current_obj()
    resp = response._current_obj()

    api = req.environ.get('repoze.who.api')
    if api:
        authentication_plugins = req.environ['repoze.who.plugins']
        try:
            identifier = authentication_plugins['main_identifier']
        except KeyError:
            raise TGConfigError('No repoze.who plugin registered as "main_identifier"')

        resp.headers.extend(api.remember({
            'repoze.who.userid': user_name,
            'identifier': identifier
        }))