sutee
sutee

Reputation: 12828

Passing along extra parameter in @view_config decorator

Is there a way to pass an extra parameter at the level of the @view_config level?

I would like to use multiple @view_config decorators for a method but pass a parameter to indicate which one has been used:

@view_config(renderer="shape.mak", route_name='circle_route')
@view_config(renderer="shape.mak", route_name='triangle route')
def new_model(self, fparams=None, ppath=None):
    #here, I'd like to capture a variable that tells me whether the cirlce or triangle route was used to access this method

I realize I can consolidate my routes (eg have a shape route) and add an extra parameter for the type of shape, but I'd like to know my options.

Upvotes: 0

Views: 341

Answers (1)

Michael Merickel
Michael Merickel

Reputation: 23331

The view configuration is intended to be declarative. This means the view doesn't know how it's being rendered, you just return the same dictionary format each time and the chosen renderer will handle it based on predicates. That being said, you can break this pattern if you wish because you can do whatever you want to in a custom_predicate.

def set_shape_predicate(shape):
    def predicate(context, request):
        request.shape = shape
        return True
    return predicate

@view_config(renderer="shape.mak", route_name='circle_route', custom_predicates=[set_shape_predicate('circle')])
@view_config(renderer="shape.mak", route_name='triangle route', custom_predicates=[set_shape_predicate('triangle')])
def new_model(self):
    # request.shape will be 'circle' or 'triangle'

You could also just check request.matched_route.name and compare it to each of the route names ('circle_route' or 'triangle_route') in a url dispatch scenario.

Upvotes: 1

Related Questions