From ff5be58d0c32eb50767fb91a49fdc72ac2cad6a4 Mon Sep 17 00:00:00 2001 From: Piotr Kopalko Date: Tue, 21 Nov 2023 20:34:03 +0100 Subject: [PATCH] Extract prefered response content type negotiation to function --- falcon/app_helpers.py | 36 ++++++++++++++++++++---------------- 1 file changed, 20 insertions(+), 16 deletions(-) diff --git a/falcon/app_helpers.py b/falcon/app_helpers.py index 38b591914..255f73b71 100644 --- a/falcon/app_helpers.py +++ b/falcon/app_helpers.py @@ -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 @@ -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: