Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions AUTHORS.rst
Original file line number Diff line number Diff line change
Expand Up @@ -60,3 +60,4 @@ Contributors (chronological)
* Tumuer `@un4gt <https://github.com/un4gt>`_
* Marat Sharafutdinov `@decaz <https://github.com/decaz>`_
* Felix Engelmann `@dorthrithil <https://github.com/dorthrithil>`_
* Vytautas Liuolia `@vytas7 <https://github.com/vytas7>`_
4 changes: 4 additions & 0 deletions CHANGELOG.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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)
******************
Expand Down
39 changes: 39 additions & 0 deletions src/webargs/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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.

Expand Down
67 changes: 28 additions & 39 deletions src/webargs/falconparser.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,11 @@

from __future__ import annotations

import inspect
import typing

import falcon
import marshmallow as ma
from falcon.util.uri import parse_query_string

from webargs import core

Expand All @@ -18,43 +20,16 @@
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


_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)


# 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
def is_json_request(req: falcon.Request) -> bool:
return core.is_json(req.content_type)


class HTTPError(falcon.HTTPError):
Expand Down Expand Up @@ -101,21 +76,35 @@ 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
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()
if inspect.isawaitable(form):
return self._makeproxy_awaitable(form, schema)
return self._makeproxy(form, 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`__.
Expand All @@ -130,7 +119,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
Expand Down Expand Up @@ -166,14 +155,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:
Expand Down
7 changes: 7 additions & 0 deletions tests/apps/falcon_app.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down Expand Up @@ -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
10 changes: 10 additions & 0 deletions tests/test_falconparser.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"}
Loading