Cornices/cornice

Handle JSON default renderer and empty response body.

Opened this issue · 5 comments

The following is more of a question and observation, with a related discussion in the Pylons group, and perhaps somewhat related is issue #470.

Here’s the thing:

@user_logout.post(
    content_type="application/json",
    accept="application/json",
    permission="logout",
    )
def user_logout_post(request):
    """Log out and invalidate the session token."""
    […]
    return HTTPOk()

Here the view returns a new HTTPOk() object (which is also an HTTPException which is also a Response); it doesn’t use the request.response object. Because of that, it seems that the default JSON renderer is not applied and the response is an HTML content type, thus contradicting the request’s Accept header.

In order to ensure a JSON response here, the view should return like so:

    # return HTTPOk()
    request.response.status = 200  # Defaults to 200, but could be 201 etc.
    return None

Returning None here causes the response to be rendered by the default JSON renderer which is what I want. However, returning None also adds a null response body, which is not what I want.

What’s the recommended way out of this dilemma? How can I use the default JSON renderer and return empty JSON responses? Is this currently doable, or would that need a Cornice patch?

@leplatrem, why the 😕? Question/issue not clear?

I'm sorry, no! I was just completely unsure of what to do about it :/

Is this the code blob where the view’s response would be checked?

Yes !

cornice/cornice/service.py

Lines 500 to 502 in ded8422

response = view_()
else:
response = view_(request)

Now that I read the code again for fixing #521, I believe that we could check the type of the returned object, and if it's an instance of Reponse then just use it. No?