c0lon
c0lon

Reputation: 210

In Pyramid, can I have multiple views point to the same route/URL based on the request method?

I've inherited a project and I'm trying to make it as clean as possible. As it is now, each view just has if/else blocks that handle the different HTTP request methods (GET, POST, DELETE, etc). I would like to have a view method that can handle not only each route, but each route + request method combination.

I'm trying this

@view_config(route_name='foo', request_method='GET', renderer='json')
def foo(request):
    return Response(json.dumps({'route' : 'foo', 'method' : 'GET'}))

@view_config(route_name='foo', request_method='POST', renderer='json')
def foo(request):
    return Response(json.dumpds({'route' : 'foo', 'method' : 'POST'}))

but it's not working. Can anyone help?

Upvotes: 1

Views: 1248

Answers (3)

Tuan Dinh
Tuan Dinh

Reputation: 418

You have to change the function name to get_foo for GET and post_foo for POST

    @view_config(route_name='foo', request_method='GET', renderer='json')
    def get_foo(request):
        return Response(json.dumps({'route' : 'foo', 'method' : 'GET'}))

   @view_config(route_name='foo', request_method='POST', renderer='json')
   def post_foo(request):
       return Response(json.dumpds({'route' : 'foo', 'method' : 'POST'}))

Upvotes: 2

Thomas Anderson
Thomas Anderson

Reputation: 74

according Paul Yin post. this is true to use @view_defaults(route_name='foo') but you dont need to use xhr=True in view_config. xhr use to handle ajax requests. also if you use json renderer no need to usding json.dump

Upvotes: 0

Paul Yin
Paul Yin

Reputation: 1759

try add xhr=True at @view_config, and you can use class view

from pyramid.view import view_config, view_defaults

@view_defaults(route_name='foo')
class TutorialViews(object):
    def __init__(self, request):
        self.request = request

    @view_config(request_method='GET', xhr=True, renderer='json')
    def foo_get(self):
        return Response(json.dumpds({'route' : 'foo', 'method' : 'GET'}))

    @view_config(request_method='POST', xhr=True, renderer='json')
    def foo_post(self):
        return Response(json.dumpds({'route' : 'foo', 'method' : 'POST'}))

Upvotes: 0

Related Questions