I have a url, call it example.com that returns a json-formatted string. I'd like to be able to pass in a parameter that lets me pretty print this json so it's more readable. I've read through the docs but something isn't sinking in for me. Here's what I have:
# config
config.add_renderer('prettyprintjson', JSON(indent=4))
# view
@view_config(route_name='home',renderer='prettyprintjson')
def home(request):
if request.params.get('pretty') == 'true': return {'name':'Fred'} # pretty print
else: return {'name':'Fred'} # how do I return a non-pretty print version???
Here the solution for your case:
@view_config(route_name='home', renderer='json')
# It's better to keep non-pretty JSON renderer as a default one
def home(request):
if request.params.get('pretty'):
request.override_renderer = 'prettyprintjson'
return {'name':'Fred'}
More info in the Overriding A Renderer At Runtime section of docs.