Inheriting the Pyramid Class Using @view_defaults and @view_config Decorators

I wrote a view class that has several @view_config with predicates set for the same route. Then I have a subclass that overwrites a couple of subfunctions, which affects how the view is created. Below is something similar, but with simplified code.

When visiting view_a route, everything works fine. When visiting the view_b route, β€œ404 Not Found” is displayed. The resource can not be found ".

It seems that @view_configs are not "inherited" and are associated with the new @view_default. Is there an easy way to fix this, or will I have to switch to manually executing 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' 
+5
source share
1 answer

@view_config is a @view_config decorator, not a strictly traditional decorator. Until it calls itself .scan() , something takes effect.

It also means that they are not inherited, however venusian provides a class decoder named lift() that will do what you need.

The venusian API documentation shows that in your use case there should be something like the following:

 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' 

At this point, all of your inherited functions will correctly apply @view_config . Now when you run .scan() your application will behave as expected.


Note that @view_defaults inheritance may change in the future: https://github.com/Pylons/pyramid/issues/1382 .

This may or may not change your views, as indicated, depending on whether you expect the renderer to migrate from the superclass.

+7
source

Source: https://habr.com/ru/post/1206137/


All Articles