I don't know what is recommended, but have done similar things before.
One way I've done something similar is to use a custom renderer in the `@view_config`.
Another way I've accomplished this is to set a request attribute early on - either in a tween or in the view class instantiation or even a request attribute, and having my return value reflect this.
To illustrate the second example, in this project each view is configured to handle 2 different API endpoints - one that is human HTML, and another that is programmatic API for JSON. If the route is accessed for JSON, the view returns a slightly different payload.
1- This code adds a "Request.wants_json" attribute:
2- This view returns a different payload, depending upon the wants_json attribute.
This was a quick, lazy and functional way to proceed. If I had to do this again, I would probably use a single payload with a custom JSON renderer, and have a function in the custom JSON renderer to only render specific values from the payload (which would either be attached to the request, or listed in a namespace in the payload).
For your description though, I would probably just write a custom JSON renderer.
For example, here is a custom jsonp and gif renderer:
def jsonp_renderer_factory(info):
def _render(value, system):
value = py2json(value)
request = system.get("request")
if request is None:
return value
# JSONP is GET only, unless you do some weird shit that doesn't work reliably
callback = request.GET.get("callback", None)
if callback is None:
ct_json = "application/json"
else:
ct_json = "application/javascript"
value = "%s(%s)" % (callback, value)
response = request.response
if response.content_type == response.default_content_type:
response.content_type = ct_json
return value
return _render
def gif_renderer_factory(info):
def _render(value, system):
request = system.get("request")
if request is not None:
response = request.response
ct = response.content_type
if ct == response.default_content_type:
response.content_type = "image/gif"
return value
return _render
config.add_renderer("jsonp", jsonp_renderer_factory)
config.add_renderer("gif", gif_renderer_factory)