本文介绍了金字塔视图类继承与@view_defaults 和@view_config 装饰器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一个视图类,该类具有多个@view_config,并为单个路由设置了谓词.然后我有一个覆盖几个子函数的子类,这会影响视图的制作方式.下面是类似的东西,但代码简化了.

I have written up a view class that has multiple @view_config's with predicates set for a single route. I then have a subclass that overwrites a couple of the sub-functions, which affects how the view is made. Below is something similar, but with simplified code.

访问 view_a 路线时,一切正常.访问view_b路由时,显示404 Not Found The resource could not be found".

When visiting the view_a route, everything works fine. When visiting the view_b route, it shows "404 Not Found The resource could not be found".

似乎@view_configs 不是继承的"并链接到新的@view_default.有没有简单的方法来解决这个问题,还是我必须切换到手动执行 config.add_view()?

It seems the @view_configs aren't 'inherited' and linked to the new @view_default. Is there a simple way to fix this, or will I have to switch to manually doing config.add_view()?

@view_defaults(route_name='view_a', renderer='templates/views.mak')
class View_A(object):

    def message(self):
        return 'This is view a'

    @view_config(request_method='GET')
    def get(self):
        return {'message': self.message()}

@view_defaults(route_name='view_b')
class View_B(View_A):

    def message(self):
        return 'This is view b'

推荐答案

@view_config 是一个 venusian 装饰器,而不是严格的传统装饰器.直到 .scan() 被调用才会生效.

@view_config is a venusian decorator, and not a strictly traditional decorator. Not until .scan() is called will anything take effect.

这也意味着它们不会被继承,但是 venusian 提供了一个名为 lift() 的类装饰器,它会完全按照你的意愿去做.

This also means that they are not inherited, however venusian provides a class decorator named lift() that will do exactly as you wish.

venusian API 文档显示类似以下内容应该可以工作对于您的用例:

The venusian API documentation shows that something like the following should work for your use case:

from venusian import lift

@view_defaults(route_name='view_a', renderer='templates/views.mak')
class View_A(object):

    def message(self):
        return 'This is view a'

    @view_config(request_method='GET')
    def get(self):
        return {'message': self.message()}

@view_defaults(route_name='view_b')
@lift()
class View_B(View_A):

    def message(self):
        return 'This is view b'

此时所有继承的函数都将正确应用@view_config.现在,在运行 .scan() 时,您的应用程序将按预期运行.

At this point all your inherited functions will correctly have the @view_config applied. Now upon running .scan() your application will behave as expected.

请注意,@view_defaults 的继承在未来可能会发生变化:https://github.com/Pylons/pyramid/issues/1382.

Do note, that the inheritance of @view_defaults may change in the future: https://github.com/Pylons/pyramid/issues/1382.

这可能会也可能不会改变您列出的视图,具体取决于您是否希望渲染器从超类继承.

This may or may not change your views as listed, depending on whether you expect the renderer to carry over from the super class.

这篇关于金字塔视图类继承与@view_defaults 和@view_config 装饰器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-26 15:46