1

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?

c0lon
  • 210
  • 1
  • 9
  • 1
    I figured it out as I was typing the question, but I thought I'd finish it out to help others. I had to rename the view methods so they were unique, so the first `foo()` became `foo_get()` and the second became `foo_post()` – c0lon Apr 06 '16 at 16:17

3 Answers3

2

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'}))
Tuan Dinh
  • 407
  • 1
  • 3
  • 13
0

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'}))
Paul Yin
  • 1,753
  • 2
  • 13
  • 19
0

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

Thomas Anderson
  • 74
  • 1
  • 1
  • 9