From b3bdfca8bc396a82492b33d78fbd06d8ce3bcfeb Mon Sep 17 00:00:00 2001 From: Vytautas Liuolia Date: Wed, 22 Jul 2026 19:49:14 +0200 Subject: [PATCH 1/4] Improve Falcon parser (work in progress) --- src/webargs/falconparser.py | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/src/webargs/falconparser.py b/src/webargs/falconparser.py index df3849a6..67bf4d54 100644 --- a/src/webargs/falconparser.py +++ b/src/webargs/falconparser.py @@ -2,6 +2,8 @@ from __future__ import annotations +import typing + import falcon import marshmallow as ma from falcon.util.uri import parse_query_string @@ -18,7 +20,7 @@ def _find_exceptions(): for name in filter(lambda n: n.startswith("HTTP"), dir(falcon.status_codes)): status = getattr(falcon.status_codes, name) - status_code = int(status.split(" ")[0]) + status_code = falcon.http_status_to_code(status) status_map[status_code] = status @@ -26,9 +28,8 @@ def _find_exceptions(): del _find_exceptions -def is_json_request(req: falcon.Request): - content_type = req.get_header("Content-Type") - return content_type and core.is_json(content_type) +def is_json_request(req: falcon.Request) -> bool: + return core.is_json(req.content_type) # NOTE: Adapted from falcon.request.Request._parse_form_urlencoded @@ -115,7 +116,9 @@ def load_form(self, req: falcon.Request, schema): def load_media(self, req: falcon.Request, schema): """Return data unpacked and parsed by one of Falcon's media handlers. - By default, Falcon only handles JSON payloads. + + By default, Falcon handles JSON, URL-encoded and multipart form payloads. + (However, :meth:`load_files` does not support Falcon's multipart form yet.) To configure additional media handlers, see the `Falcon documentation on media types`__. @@ -130,7 +133,7 @@ def load_media(self, req: falcon.Request, schema): # if there is no body, return missing instead of erroring if req.content_length in (None, 0): return core.missing - return req.media + return req.get_media() def _raw_load_json(self, req: falcon.Request): """Return a json payload from the request for the core parser's load_json @@ -166,14 +169,14 @@ def get_request_from_view_args(self, view, args, kwargs): raise TypeError("Argument is not a falcon.Request") return req - def load_files(self, req: falcon.Request, schema): + def load_files(self, req: falcon.Request, schema) -> typing.NoReturn: raise NotImplementedError( f"Parsing files not yet supported by {self.__class__.__name__}" ) def handle_error( self, error, req: falcon.Request, schema, *, error_status_code, error_headers - ): + ) -> typing.NoReturn: """Handles errors during parsing.""" status = status_map.get(error_status_code or self.DEFAULT_VALIDATION_STATUS) if status is None: From 15c11de7de07ad7e0a1e441f1f8f28fbe1d56894 Mon Sep 17 00:00:00 2001 From: Stephen Rosen Date: Fri, 13 Nov 2026 17:00:03 -0600 Subject: [PATCH 2/4] Simplify Falcon load_form by relying on get_media We can rely on Falcon's handling of form posts for `load_form` so long as we define some parameters around it. Based on discussion, it seems like the simplest option is to skip support for multipart forms, directing any users to use `load_media` instead, and to make `load_form` use the underlying `get_media` call after checking the content type. The content-type check is the same loose one which was present before. Remove the `parse_form_body` helper, as no longer needed. --- CHANGELOG.rst | 4 ++++ src/webargs/falconparser.py | 43 +++++++++++-------------------------- 2 files changed, 17 insertions(+), 30 deletions(-) diff --git a/CHANGELOG.rst b/CHANGELOG.rst index dc165b6f..2f290723 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -33,6 +33,10 @@ Other changes: * Drop support for Falcon < 4.1.0 (:pr:`1023`). * Drop support for aiohttp < 3.13.0 (:pr:`1023`). * Drop support for marshmallow < 4.0.0 (:pr:`1023`). +* The Falcon parser has been improved and simplified. In particular, `load_form` + now uses Falcon's `get_media` method after checking the media type. This means + that Falcon users who customize media handling will see their customizations + present in data loaded with `location="form"`. (:pr:`1080`) 8.7.1 (2025-10-29) ****************** diff --git a/src/webargs/falconparser.py b/src/webargs/falconparser.py index 67bf4d54..18a6d71b 100644 --- a/src/webargs/falconparser.py +++ b/src/webargs/falconparser.py @@ -6,7 +6,6 @@ import falcon import marshmallow as ma -from falcon.util.uri import parse_query_string from webargs import core @@ -32,32 +31,6 @@ def is_json_request(req: falcon.Request) -> bool: return core.is_json(req.content_type) -# NOTE: Adapted from falcon.request.Request._parse_form_urlencoded -def parse_form_body(req: falcon.Request): - if ( - req.content_type is not None - and "application/x-www-form-urlencoded" in req.content_type - ): - # the type of `req.stream.read()` is `str | Any` according to annotations - # but at runtime it's always `bytes`, so coerce the type for type checker - body: str | bytes | None = req.stream.read(req.content_length or 0) - try: - body = body.decode("ascii") # type: ignore[union-attr] - except UnicodeDecodeError: - body = None - req.log_error( - "Non-ASCII characters found in form body " - "with Content-Type of " - "application/x-www-form-urlencoded. Body " - "will be ignored." - ) - - if body: - return parse_query_string(body, keep_blank=req.options.keep_blank_qs_values) - - return core.missing - - class HTTPError(falcon.HTTPError): """HTTPError that stores a dictionary of validation error messages.""" @@ -105,13 +78,23 @@ def load_querystring(self, req: falcon.Request, schema): def load_form(self, req: falcon.Request, schema): """Return form values from the request as a MultiDictProxy + This uses Falcon's media type handling, but requires that the media type is + specifically form data. Multipart forms are not supported via this method: use + ``load_media`` and Falcon's media type handling for that use case. + .. note:: The request stream will be read and left at EOF. """ - form = parse_form_body(req) - if form is core.missing: - return form + # if we do not see the canonical form media type, return 'missing', as there + # is no form data + if ( + req.content_type is None + or "application/x-www-form-urlencoded" not in req.content_type + ): + return core.missing + + form = req.get_media() return self._makeproxy(form, schema) def load_media(self, req: falcon.Request, schema): From d01ea5b49049cd5914afb5f3a8aca011aa5b6dae Mon Sep 17 00:00:00 2001 From: Stephen Rosen Date: Fri, 13 Nov 2026 17:16:50 -0600 Subject: [PATCH 3/4] Add Vytas to authors, as a contributor --- AUTHORS.rst | 1 + 1 file changed, 1 insertion(+) diff --git a/AUTHORS.rst b/AUTHORS.rst index f487ea23..2a79f411 100644 --- a/AUTHORS.rst +++ b/AUTHORS.rst @@ -60,3 +60,4 @@ Contributors (chronological) * Tumuer `@un4gt `_ * Marat Sharafutdinov `@decaz `_ * Felix Engelmann `@dorthrithil `_ +* Vytautas Liuolia `@vytas7 `_ From 5f8ea6f4b7f4892989b25618b4e0b02d62d1aec3 Mon Sep 17 00:00:00 2001 From: Stephen Rosen Date: Fri, 13 Nov 2026 19:30:54 -0600 Subject: [PATCH 4/4] Improve falcon parser: support async form data When used in an async parser / async app, it is possible for the falcon parser's `load_form` to be called within an async app. In such a case, `get_media()` returns an awaitable, and failing to handle this results in an error. 1. Add a missing unit test which confirms that you can use the "form" location inside of an async application. 2. Wrap the result of `load_form()` as a coroutine to make it awaitable, where awaiting the coroutine awaits the underlying falcon-provided object. In order to make (2) into a reusable paradigm, it's now implemented on the base parser as a sibling of `_makeproxy` (which builds multidict proxies), `_makeproxy_awaitable`. Additionally, this improves the typing applied to `_makeproxy` as a side-benefit from exploring better typing and overloads. --- src/webargs/core.py | 39 +++++++++++++++++++++++++++++++++++++ src/webargs/falconparser.py | 5 ++++- tests/apps/falcon_app.py | 7 +++++++ tests/test_falconparser.py | 10 ++++++++++ 4 files changed, 60 insertions(+), 1 deletion(-) diff --git a/src/webargs/core.py b/src/webargs/core.py index 96a4516e..12ce6aef 100644 --- a/src/webargs/core.py +++ b/src/webargs/core.py @@ -196,6 +196,16 @@ def __init__( self.schema_class = schema_class or self.DEFAULT_SCHEMA_CLASS self.unknown = unknown + @typing.overload + def _makeproxy( + self, multidict: typing.Any, schema: ma.Schema + ) -> MultiDictProxy: ... + + @typing.overload + def _makeproxy( + self, multidict: typing.Any, schema: ma.Schema, *, cls: type[MultiDictProxyT] + ) -> MultiDictProxyT: ... + def _makeproxy( self, multidict: typing.Any, @@ -206,6 +216,35 @@ def _makeproxy( """Create a multidict proxy object with options from the current parser""" return cls(multidict, schema, known_multi_fields=tuple(self.KNOWN_MULTI_FIELDS)) + @typing.overload + def _makeproxy_awaitable( + self, multidict: typing.Any, schema: ma.Schema + ) -> typing.Awaitable[MultiDictProxy]: ... + + @typing.overload + def _makeproxy_awaitable( + self, multidict: typing.Any, schema: ma.Schema, *, cls: type[MultiDictProxyT] + ) -> typing.Awaitable[MultiDictProxyT]: ... + + def _makeproxy_awaitable( + self, + multidict: typing.Any, + schema: ma.Schema, + *, + cls: type[MultiDictProxyT] | type[MultiDictProxy] = MultiDictProxy, + ) -> typing.Awaitable[MultiDictProxyT | MultiDictProxy]: + """Create a multidict proxy object, wrapped in a coroutine which awaits the + multidict data, with options from the current parser.""" + + async def await_multidict() -> MultiDictProxyT | MultiDictProxy: + return cls( + await multidict, + schema, + known_multi_fields=tuple(self.KNOWN_MULTI_FIELDS), + ) + + return await_multidict() + def _get_loader(self, location: str) -> typing.Callable: """Get the loader function for the given location. diff --git a/src/webargs/falconparser.py b/src/webargs/falconparser.py index 18a6d71b..d5fce204 100644 --- a/src/webargs/falconparser.py +++ b/src/webargs/falconparser.py @@ -2,6 +2,7 @@ from __future__ import annotations +import inspect import typing import falcon @@ -75,7 +76,7 @@ def load_querystring(self, req: falcon.Request, schema): """Return query params from the request as a MultiDictProxy.""" return self._makeproxy(req.params, schema) - def load_form(self, req: falcon.Request, schema): + def load_form(self, req: falcon.Request, schema: ma.Schema): """Return form values from the request as a MultiDictProxy This uses Falcon's media type handling, but requires that the media type is @@ -95,6 +96,8 @@ def load_form(self, req: falcon.Request, schema): return core.missing form = req.get_media() + if inspect.isawaitable(form): + return self._makeproxy_awaitable(form, schema) return self._makeproxy(form, schema) def load_media(self, req: falcon.Request, schema): diff --git a/tests/apps/falcon_app.py b/tests/apps/falcon_app.py index 62746f0d..58b158a5 100644 --- a/tests/apps/falcon_app.py +++ b/tests/apps/falcon_app.py @@ -41,6 +41,12 @@ def on_post(self, req, resp): set_text(resp, json.dumps(parsed)) +class AsyncEchoForm: + async def on_post(self, req, resp): + parsed = await parser.async_parse(hello_args, req, location="form") + set_text(resp, json.dumps(parsed)) + + class EchoJSON: def on_post(self, req, resp): parsed = parser.parse(hello_args, req, location="json") @@ -217,4 +223,5 @@ def create_async_app(): app = falcon.asgi.App() app.add_route("/async_echo", AsyncEcho()) app.add_route("/async_echo_use_args", AsyncEchoUseArgs()) + app.add_route("/async_echo_form", AsyncEchoForm()) return app diff --git a/tests/test_falconparser.py b/tests/test_falconparser.py index 7e291a18..a76c0e1a 100644 --- a/tests/test_falconparser.py +++ b/tests/test_falconparser.py @@ -86,3 +86,13 @@ def test_async_use_args_decorator(self): assert client.simulate_get("/async_echo_use_args?name=Fred").json == { "name": "Fred" } + + @pytest.mark.usefixtures("current_loop") + def test_parse_form_args_async(self): + app = create_async_app() + client = falcon.testing.TestClient(app) + assert client.simulate_post( + "/async_echo_form", + body="name=Fred", + headers={"Content-Type": "application/x-www-form-urlencoded"}, + ).json == {"name": "Fred"}