Skip to content

Commit

Permalink
Extract prefered response content type negotiation to function
Browse files Browse the repository at this point in the history
  • Loading branch information
copalco committed Dec 3, 2023
1 parent f77518f commit ff5be58
Showing 1 changed file with 20 additions and 16 deletions.
36 changes: 20 additions & 16 deletions falcon/app_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -226,8 +226,26 @@ def default_serialize_error(req: Request, resp: Response, exception: HTTPError):
resp: Instance of ``falcon.Response``
exception: Instance of ``falcon.HTTPError``
"""
preferred = req.client_prefers((MEDIA_XML, 'text/xml', MEDIA_JSON))
preferred = _negotiate_preffered_media_type(req)

if preferred is not None:
if preferred == MEDIA_JSON:
handler, _, _ = resp.options.media_handlers._resolve(
MEDIA_JSON, MEDIA_JSON, raise_not_found=False
)
resp.data = exception.to_json(handler)
else:
resp.data = exception.to_xml()

# NOTE(kgriffs): No need to append the charset param, since
# utf-8 is the default for both JSON and XML.
resp.content_type = preferred

resp.append_header('Vary', 'Accept')


def _negotiate_preffered_media_type(req: Request) -> str:
preferred = req.client_prefers((MEDIA_XML, 'text/xml', MEDIA_JSON))
if preferred is None:
# NOTE(kgriffs): See if the client expects a custom media
# type based on something Falcon supports. Returning something
Expand All @@ -246,21 +264,7 @@ def default_serialize_error(req: Request, resp: Response, exception: HTTPError):
preferred = MEDIA_JSON
elif '+xml' in accept:
preferred = MEDIA_XML

if preferred is not None:
if preferred == MEDIA_JSON:
handler, _, _ = resp.options.media_handlers._resolve(
MEDIA_JSON, MEDIA_JSON, raise_not_found=False
)
resp.data = exception.to_json(handler)
else:
resp.data = exception.to_xml()

# NOTE(kgriffs): No need to append the charset param, since
# utf-8 is the default for both JSON and XML.
resp.content_type = preferred

resp.append_header('Vary', 'Accept')
return preferred


class CloseableStreamIterator:
Expand Down

0 comments on commit ff5be58

Please sign in to comment.