Search code examples
http-redirectweb2py

Web2py return json or redirect


In web2py, I want to set up a controller that redirects for an html view but provides a json response for a json view, e.g.

http://mysite/page.html/1234 -> redirects to http://www.google.com/q=mydata http://mysite/page.json/1234 -> returns JSON {'1234':'my data'}

(this example assumes I have a db query that returns 'mydata' for id=1234)

I can't immediately see how to do this, as the redirect() function is called in the controller, but the decision about json or html seems to be made later, once a dict() is returned from the controller


Solution

  • In the controller you can use request.extension to decide whether to redirect() or return response.json(my_data).