• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python decorators.Decoration类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中tg.decorators.Decoration的典型用法代码示例。如果您正苦于以下问题:Python Decoration类的具体用法?Python Decoration怎么用?Python Decoration使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了Decoration类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: __init__

    def __init__(self, *args, **kw):
        super(RoutedController, self).__init__(*args, **kw)

        routes = []
        for name in dir(self):
            value = getattr(self.__class__, name, None)
            if value is None:
                continue

            deco = None
            if inspect.ismethod(value):  # pragma: no cover
                # PY2
                deco = Decoration.get_decoration(value.__func__)
            elif inspect.isfunction(value):  # pragma: no cover
                # PY3
                deco = Decoration.get_decoration(value)

            if deco is None:
                continue

            if hasattr(deco, '_tgext_routes'):
                routes.extend(deco._tgext_routes)

        if routes:
            instance_mapper = Mapper()
            if self.mapper is not None:
                instance_mapper.extend(self.mapper.matchlist)
            instance_mapper.extend(routes)
            self.mapper = instance_mapper
开发者ID:TurboGears,项目名称:tgext.routes,代码行数:29,代码来源:dispatch.py


示例2: test_backward_compatibility_decorator

    def test_backward_compatibility_decorator(self):
        deco = Decoration.get_decoration(BasicTGController.two_validators)

        validated_params = sorted(list(deco.validation.validators.keys()))
        assert validated_params == ["a", "someemail"], validated_params

        deco = Decoration.get_decoration(BasicTGController.tw2form_error_handler)
        assert deco.validation is None, deco.validation
开发者ID:984958198,项目名称:tg2,代码行数:8,代码来源:test_validation.py


示例3: __call__

    def __call__(self):
        log.debug("Registering %s for hook %s on controller %s",
                  self.func, self.hook_name, self.controller)

        if self.hook_name == 'controller_wrapper':
            deco = Decoration.get_decoration(self.controller)
            deco._register_controller_wrapper(self.func)
        else:
            deco = Decoration.get_decoration(self.controller)
            deco._register_hook(self.hook_name, self.func)
开发者ID:garrettmc,项目名称:TGWikiTutorial,代码行数:10,代码来源:hooks.py


示例4: notify_with_value

    def notify_with_value(self, hook_name, value, controller=None, context_config=None):
        """Notifies a TurboGears hook which is expected to return a value.

        hooks with values are expected to accept an input value an return
        a replacement for it. Each registered function will receive as input
        the value returned by the previous function in chain.

        The resulting value will be returned by the ``notify_with_value``
        call itself::

            app = tg.hooks.notify_with_value('before_config', app)

        """
        if context_config is None: #pragma: no cover
            context_config = tg.config._current_obj()

        try:
            syswide_hooks = context_config['hooks'][hook_name]
            for func in syswide_hooks:
                value = func(value)
        except KeyError: #pragma: no cover
            pass

        if controller is not None:
            controller = default_im_func(controller)
            deco = Decoration.get_decoration(controller)
            for func in deco.hooks[hook_name]:
                value = func(value)

        return value
开发者ID:Shamefox,项目名称:tg2,代码行数:30,代码来源:hooks.py


示例5: notify

    def notify(self, hook_name, args=None, kwargs=None, controller=None, context_config=None):
        """Notifies a TurboGears hook.

        Each function registered for the given hook will be executed,
        ``args`` and ``kwargs`` will be passed to the registered functions
        as arguments.

        It permits to notify both application hooks::

            tg.hooks.notify('custom_global_hook')

        Or controller hooks::

            tg.hooks.notify('before_render', args=(remainder, params, output),
                            controller=RootController.index)

        """
        if context_config is None: #pragma: no cover
            context_config = tg.config._current_obj()

        args = args or []
        kwargs = kwargs or {}

        try:
            syswide_hooks = context_config['hooks'][hook_name]
            for func in syswide_hooks:
                func(*args, **kwargs)
        except KeyError: #pragma: no cover
            pass

        if controller is not None:
            controller = default_im_func(controller)
            deco = Decoration.get_decoration(controller)
            for func in deco.hooks.get(hook_name, []):
                func(*args, **kwargs)
开发者ID:Shamefox,项目名称:tg2,代码行数:35,代码来源:hooks.py


示例6: plugin

    def plugin(f, *args, **kw):
        results_dict = f(*args, **kw)
        user = args[0].user
        residence_var = "residence"
       
        plugins_templates = list()

        # un plugin est defini pour le scope et residence est defini 
        if scope in plugins_config.mappings and residence_var in results_dict:
            residence_dn = Residences.get_dn_by_name(user, results_dict[residence_var])

            scope_mappings = plugins_config.mappings[scope]
            
            for function in scope_mappings:
                plugin_name = plugin_name_from_function(function)

                plugin_activated = Plugins.get_by_name(user, residence_dn, plugin_name)

                if plugin_activated is None:
                    continue
                #end if

                template_name = None

                # obtenir le nom du template à partir du decorator "expose"
                deco = Decoration.get_decoration(function)
                try:
                    template_name = deco.engines["text/html"][1]
                except:
                    pass

                if template_name is not None:
                    # transformer le nom de template en chemin fichier
                    template_path = (
                        tg.config['pylons.app_globals']
                          .dotted_filename_finder
                          .get_dotted_filename(template_name, template_extension='.html')
                    )

                    # ajouter dans les plugin templates
                    plugins_templates.append(template_path)
                #end if

                # executer la fonction du plugin
                mapping_results = function(results_dict)

                # constuire le nom de regroupement des variable de ce plugin
                method_name = function.__name__
                plugin_section = str.lower(plugin_name + "_" + method_name)

                # ajout du groupe au dictionnaire de la methode du controlleur
                results_dict[plugin_section] = PluginVars(mapping_results)
            #end for

        #end if

        # ajout des templates dans un champs spécial du dictionnaire pour le rendu
        results_dict["_plugins_templates"] = plugins_templates

        return results_dict
开发者ID:Rbeuque74,项目名称:brie-aurore,代码行数:60,代码来源:plugins.py


示例7: test_no_requirements_backward_compatibility

 def test_no_requirements_backward_compatibility(self):
     deco = Decoration.get_decoration(RootController.force_commit)
     reqs = deco.requirements
     deco.requirements = []
     requirement = deco.requirement
     deco.requirements = reqs
     assert requirement is None, requirement
开发者ID:garrettmc,项目名称:TGWikiTutorial,代码行数:7,代码来源:test_authz.py


示例8: __call__

    def __call__(self, path, **params):
        config = tg.config._current_obj()
        try:
            func = config['_pluggable_partials_cache'][path]
        except:
            func = config['_pluggable_partials_cache'][path] = self.resolve(path)

        result = func(**params)
        
        if not isinstance(result, dict):
            return result

        #Expect partials not to expose more than one template
        available_engines = list(Decoration.get_decoration(func).engines.values())
        engine_name, template_name, exclude_names = available_engines[0][:3]
        replaced_template = config.get('_pluggable_templates_replacements', {}).get(template_name)
        if replaced_template:
            engine_name, template_name = replaced_template.split(':', 1)

        #Avoid placing the doctype declaration in genshi templates
        render_params = {}
        if engine_name == 'genshi':
            render_params['doctype'] = None

        return tg_render(template_vars=result, template_engine=engine_name, template_name=template_name,
                         **render_params)
开发者ID:RobertSudwarts,项目名称:tgext.pluggable,代码行数:26,代码来源:utils.py


示例9: test_lazy_inheritance_with_3nested_template

    def test_lazy_inheritance_with_3nested_template(self):
        milestones.renderers_ready._reset()

        class BaseController(tg.TGController):
            @tg.expose('template.html')
            @tg.expose('template.html', content_type='text/plain')
            @tg.expose('template.html', content_type='text/javascript')
            def func(self):
                pass

        class SubController(BaseController):
            @tg.expose('new_template.html', inherit=True)
            @tg.expose('new_template.html', content_type='text/plain')
            @tg.expose('new_template.html', content_type='text/javascript')
            def func(self):
                pass

        class SubSubController(SubController):
            @tg.expose('new2_template.html', inherit=True)
            @tg.expose('new2_template.html', content_type='text/javascript')
            def func(self):
                pass

        class SubSubSubController(SubSubController):
            @tg.expose('new3_template.html', inherit=True)
            def func(self):
                pass

        milestones.renderers_ready.reach()

        deco = Decoration.get_decoration(SubSubSubController.func)
        assert len(deco.engines) == 3, deco.engines
        assert deco.engines['text/html'][1] == 'new3_template.html', deco.engines
        assert deco.engines['text/plain'][1] == 'new_template.html', deco.engines
        assert deco.engines['text/javascript'][1] == 'new2_template.html', deco.engines
开发者ID:984958198,项目名称:tg2,代码行数:35,代码来源:test_decorators.py


示例10: __call__

 def __call__(self, func):
     deco = decorator(self.wrap, func)
     exposed = Decoration.get_decoration(deco)
     deco.signatures = self.signatures
     deco.helpstr = self.helpstr
     exposed.register_template_engine(\
         'text/xml', config.get('default_renderer', ['mako'])[0],
         '', [], {})
     return deco
开发者ID:TurboGears,项目名称:tgext.xmlrpc,代码行数:9,代码来源:controllers.py


示例11: __call__

 def __call__(self, func):
     deco = Decoration.get_decoration(func)
     if not hasattr(deco, '_tgext_routes'):
         deco._tgext_routes = []
     deco._tgext_routes.append(Route(func.__name__,
                                     self.routing_path,
                                     controller=route.CURRENT_CONTROLLER,
                                     action=func.__name__,
                                     **self.routing_args))
     return func
开发者ID:TurboGears,项目名称:tgext.routes,代码行数:10,代码来源:decorators.py


示例12: __call__

    def __call__(self):
        log.debug("Registering %s for hook %s on controller %s",
                  self.func, self.hook_name, self.controller)

        if self.hook_name == 'controller_wrapper':
            config = tg.config._current_obj()
            dedicated_wrappers = config['dedicated_controller_wrappers']
            dedicated_wrappers.setdefault(self.controller, []).append(self.func)
        else:
            deco = Decoration.get_decoration(self.controller)
            deco._register_hook(self.hook_name, self.func)
开发者ID:Shamefox,项目名称:tg2,代码行数:11,代码来源:hooks.py


示例13: render_widget

def render_widget(mount_point, widget_name):
    app = c.project.app_instance(mount_point)
    method = getattr(app.widget(app), widget_name)
    with push_config(c, app=app):
        result = method()
    if isinstance(result, dict):
        deco = Decoration.get_decoration(method)
        content_type, engine, template, exclude_names = \
            deco.lookup_template_engine(request)
        template_vars = dict((k,v) for k,v in result.iteritems()
                             if k not in exclude_names)
        return render(template_vars, engine, template)
    return result
开发者ID:pombredanne,项目名称:SourceForge-Allura,代码行数:13,代码来源:dashboard.py


示例14: test_decoration_run_hooks_backward_compatibility

    def test_decoration_run_hooks_backward_compatibility(self):
        # TODO: Remove test when Decoration.run_hooks gets removed

        def func(*args, **kw):
            pass

        def hook(*args, **kw):
            hook.did_run = True
        hook.did_run = False

        milestones.renderers_ready.reach()
        tg.hooks.register('before_call', hook, controller=func)

        deco = Decoration.get_decoration(func)
        deco.run_hooks(Bunch(config=None), 'before_call')

        assert hook.did_run is True
开发者ID:Shamefox,项目名称:tg2,代码行数:17,代码来源:test_decorated_controller.py


示例15: test_lazy_inheritance

    def test_lazy_inheritance(self):
        milestones.renderers_ready._reset()

        class BaseController(tg.TGController):
            @tg.expose('template.html')
            def func(self):
                pass

        class SubController(BaseController):
            @tg.expose(inherit=True)
            def func(self):
                pass

        milestones.renderers_ready.reach()

        deco = Decoration.get_decoration(SubController.func)
        assert len(deco.engines) == 1, deco.engines
        assert deco.engines['text/html'][1] == 'template.html', deco.engines
开发者ID:984958198,项目名称:tg2,代码行数:18,代码来源:test_decorators.py


示例16: replace_template_hook

def replace_template_hook(remainder, params, output):
    req = request._current_obj()

    try:
        dispatch_state = req._controller_state
    except:
        dispatch_state = req.controller_state

    decoration = Decoration.get_decoration(dispatch_state.method)

    if 'tg.locals' in req.environ:
        content_type, engine, template, exclude_names = decoration.lookup_template_engine(req.environ['tg.locals'])[:4]
    else:
        content_type, engine, template, exclude_names = decoration.lookup_template_engine(req)[:4]

    replaced_template = config._pluggable_templates_replacements.get(template)
    if replaced_template:
        override_template(dispatch_state.method, replaced_template)
开发者ID:kadams54,项目名称:tgext.pluggable,代码行数:18,代码来源:template_replacements.py


示例17: __call__

    def __call__(self, path, **params):
        config = tg.config._current_obj()
        try:
            func = config['_pluggable_partials_cache'][path]
        except:
            func = config['_pluggable_partials_cache'][path] = self.resolve(path)

        result = func(**params)
        
        if not isinstance(result, dict):
            return result

        #Expect partials not to expose more than one template
        engine_name, template_name, exclude_names = Decoration.get_decoration(func).engines.values()[0][:3]
        replaced_template = config.get('_pluggable_templates_replacements', {}).get(template_name)
        if replaced_template:
            engine_name, template_name = replaced_template.split(':', 1)
        return tg_render(template_vars=result, template_engine=engine_name, template_name=template_name, doctype=None)
开发者ID:mbbui,项目名称:Jminee,代码行数:18,代码来源:utils.py


示例18: add_expose_info

def add_expose_info(app, what, name, obj, options, lines):
    if (what != 'method' or not hasattr(obj, 'decoration')
        or not obj.im_class.__name__.endswith('Controller')):
        return

    deco = Decoration.get_decoration(obj)

    if not hasattr(deco, 'expose'):
        return

    try:
        # TODO: This ignores all but the first tmpl engine
        engine = deco.engines.values()[0]
        if engine[0] == 'genshi':
            template = engine[1]
            lines.append("\n")
            lines.append("\n")
            lines.append("Renders: :data:`%s`" % template)
    except:
        pass
开发者ID:SergeyLashin,项目名称:mediacore,代码行数:20,代码来源:autodoc_expose.py


示例19: test_expose_idempotent

    def test_expose_idempotent(self):
        base_config = TestConfig(folder = 'dispatch',
            values = {'use_sqlalchemy': False,
                      'use_toscawidgets': False,
                      'use_toscawidgets2': False,
                      'ignore_parameters': ["ignore", "ignore_me"]
            })

        app = app_from_config(base_config)

        exposition = tg.expose('nonexisting')

        @exposition
        @exposition
        def func(*args, **kw):
            pass

        milestones.renderers_ready.reach()

        deco = Decoration.get_decoration(func)
        assert len(deco.engines) == 1, deco.engines
开发者ID:Shamefox,项目名称:tg2,代码行数:21,代码来源:test_decorated_controller.py


示例20: register_controller_wrapper

    def register_controller_wrapper(self, wrapper, controller=None):
        """Registers a TurboGears controller wrapper.

        Controller Wrappers are much like a **decorator** applied to
        every controller.
        They receive 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(caller):
                def call(*args, **kw):
                    try:
                        print 'Before handler!'
                        return caller(*args, **kw)
                    finally:
                        print 'After Handler!'
                return call

            base_config.register_controller_wrapper(controller_wrapper)

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

            base_config.register_controller_wrapper(controller_wrapper, controller=RootController.index)
        """
        if milestones.environment_loaded.reached:
            log.warning('Controller Wrapper %s registered after environment loaded '
                        'milestone has been reached, the wrapper will be used only '
                        'for future TGApp instances.', wrapper)

        log.debug("Registering %s controller wrapper for controller: %s",
                  wrapper, controller or 'ALL')

        if controller is None:
            self._controller_wrappers.append(wrapper)
        else:
            from tg.decorators import Decoration
            deco = Decoration.get_decoration(controller)
            deco._register_controller_wrapper(wrapper)
开发者ID:TurboGears,项目名称:tg2,代码行数:40,代码来源:dispatch.py



注:本文中的tg.decorators.Decoration类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python session.get函数代码示例发布时间:2022-05-27
下一篇:
Python transformations.quaternion_about_axis函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap