Skip to content

Commit

Permalink
docs: improve docstring for option classes (#2290)
Browse files Browse the repository at this point in the history
* docs: improve request options attribute docs

* docs: improve response options attribute docs

* docs: improve websocket options attribute docs

* docs: improve multipart options attribute docs

* docs: improve compiled router options attribute docs

* fix: avoid circular import

* docs: cleanups

* style: fix pep error

* refactor: improve type after master merge

---------

Co-authored-by: Vytautas Liuolia <[email protected]>
  • Loading branch information
CaselIT and vytas7 authored Aug 23, 2024
1 parent 002d37f commit a452a2d
Show file tree
Hide file tree
Showing 6 changed files with 179 additions and 172 deletions.
2 changes: 1 addition & 1 deletion docs/api/app.rst
Original file line number Diff line number Diff line change
Expand Up @@ -48,4 +48,4 @@ Options

.. _compiled_router_options:
.. autoclass:: falcon.routing.CompiledRouterOptions
:noindex:
:members:
66 changes: 36 additions & 30 deletions falcon/asgi/ws.py
Original file line number Diff line number Diff line change
Expand Up @@ -534,30 +534,39 @@ class WebSocketOptions:
An instance of this class is exposed via :attr:`falcon.asgi.App.ws_options`
for configuring certain :py:class:`~.WebSocket` behaviors.
"""

Attributes:
error_close_code (int): The WebSocket close code to use when an
unhandled error is raised while handling a WebSocket connection
(default ``1011``). For a list of valid close codes and ranges,
see also: https://tools.ietf.org/html/rfc6455#section-7.4
default_close_reasons (dict): A default mapping between the Websocket
close code and the reason why the connection is close.
Close codes corresponding to HTTP errors are also included in this
mapping.
media_handlers (dict): A dict-like object for configuring media handlers
according to the WebSocket payload type (TEXT vs. BINARY) of a
given message. See also: :ref:`ws_media_handlers`.
max_receive_queue (int): The maximum number of incoming messages to
enqueue if the reception rate exceeds the consumption rate of the
application (default ``4``). When this limit is reached, the
framework will wait to accept new messages from the ASGI server
until the application is able to catch up.
This limit applies to Falcon's incoming message queue, and should
generally be kept small since the ASGI server maintains its
own receive queue. Falcon's queue can be disabled altogether by
setting `max_receive_queue` to ``0``
(see also: :ref:`ws_lost_connection`).
error_close_code: int
"""The WebSocket close code to use when an unhandled error is raised while
handling a WebSocket connection (default ``1011``).
For a list of valid close codes and ranges, see also:
https://tools.ietf.org/html/rfc6455#section-7.4.
"""
default_close_reasons: Dict[int, str]
"""A default mapping between the Websocket close code, and the reason why
the connection is closed.
Close codes corresponding to HTTP errors are also included in this mapping.
"""
media_handlers: Dict[
WebSocketPayloadType, Union[media.TextBaseHandlerWS, media.BinaryBaseHandlerWS]
]
"""A dict-like object for configuring media handlers according to the WebSocket
payload type (TEXT vs. BINARY) of a given message.
See also: :ref:`ws_media_handlers`.
"""
max_receive_queue: int
"""The maximum number of incoming messages to enqueue if the reception rate
exceeds the consumption rate of the application (default ``4``).
When this limit is reached, the framework will wait to accept new messages
from the ASGI server until the application is able to catch up.
This limit applies to Falcon's incoming message queue, and should
generally be kept small since the ASGI server maintains its
own receive queue. Falcon's queue can be disabled altogether by
setting `max_receive_queue` to ``0`` (see also: :ref:`ws_lost_connection`).
"""

__slots__ = [
Expand Down Expand Up @@ -598,10 +607,7 @@ def __init__(self) -> None:
'default WebSocket media handler for BINARY payloads', 'msgpack'
)

self.media_handlers: Dict[
WebSocketPayloadType,
Union[media.TextBaseHandlerWS, media.BinaryBaseHandlerWS],
] = {
self.media_handlers = {
WebSocketPayloadType.TEXT: media.JSONHandlerWS(),
WebSocketPayloadType.BINARY: bin_handler,
}
Expand All @@ -610,8 +616,8 @@ def __init__(self) -> None:
#
# See also: https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent
#
self.error_close_code: int = WSCloseCode.SERVER_ERROR
self.default_close_reasons: Dict[int, str] = self._init_default_close_reasons()
self.error_close_code = WSCloseCode.SERVER_ERROR
self.default_close_reasons = self._init_default_close_reasons()

# NOTE(kgriffs): The websockets library itself will buffer, so we keep
# this value fairly small by default to mitigate buffer bloat. But in
Expand All @@ -625,7 +631,7 @@ def __init__(self) -> None:
# * https://websockets.readthedocs.io/en/stable/design.html#buffers
# * https://websockets.readthedocs.io/en/stable/deployment.html#buffers
#
self.max_receive_queue: int = 4
self.max_receive_queue = 4


class _BufferedReceiver:
Expand Down
53 changes: 33 additions & 20 deletions falcon/media/multipart.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,10 @@

"""Multipart form media handler."""

from __future__ import annotations

import re
from typing import TYPE_CHECKING
from urllib.parse import unquote_to_bytes

from falcon import errors
Expand All @@ -25,6 +28,8 @@
from falcon.util import misc
from falcon.util.mediatypes import parse_header

if TYPE_CHECKING:
from falcon.media.handlers import Handlers
# TODO(vytas):
# * Better support for form-wide charset setting
# * Clean up, simplify, and optimize BufferedReader
Expand Down Expand Up @@ -541,33 +546,41 @@ class MultipartParseOptions:
it instantiates.
See also: :ref:`multipart_parser_conf`.
"""

Attributes:
default_charset (str): The default character encoding for
:meth:`text fields <BodyPart.get_text>` (default: ``utf-8``).
_DEFAULT_HANDLERS = None

max_body_part_count (int): The maximum number of body parts in the form
(default: 64). If the form contains more parts than this number,
an instance of :class:`.MultipartParseError` will be raised. If this
option is set to 0, no limit will be imposed by the parser.
default_charset: str
"""The default character encoding for
:meth:`text fields <BodyPart.get_text>` (default ``utf-8``).
"""
max_body_part_count: int
"""The maximum number of body parts in the form (default ``64``).
max_body_part_buffer_size (int): The maximum number of bytes to buffer
and return when the :meth:`BodyPart.get_data` method is called
(default: 1 MiB). If the body part size exceeds this value, an
instance of :class:`.MultipartParseError` will be raised.
If the form contains more parts than this number, an instance of
:class:`.MultipartParseError` will be raised. If this option is set to 0,
no limit will be imposed by the parser.
"""
max_body_part_buffer_size: int
"""The maximum number of bytes to buffer and return when the
:meth:`BodyPart.get_data` method is called (default ``1 MiB``).
max_body_part_headers_size (int): The maximum size (in bytes) of the
body part headers structure (default: 8192). If the body part
headers size exceeds this value, an instance of
:class:`.MultipartParseError` will be raised.
If the body part size exceeds this value, an instance of
:class:`.MultipartParseError` will be raised.
"""
max_body_part_headers_size: int
"""The maximum size (in bytes) of the body part headers structure
(default ``8192``).
media_handlers (Handlers): A dict-like object for configuring the
media-types to handle. By default, handlers are provided for the
``application/json`` and ``application/x-www-form-urlencoded``
media types.
If the body part headers size exceeds this value, an instance of
:class:`.MultipartParseError` will be raised.
"""
media_handlers: Handlers
"""A dict-like object for configuring the media-types to handle.
_DEFAULT_HANDLERS = None
By default, handlers are provided for the ``application/json`` and
``application/x-www-form-urlencoded`` media types.
"""

__slots__ = (
'default_charset',
Expand Down
148 changes: 70 additions & 78 deletions falcon/request.py
Original file line number Diff line number Diff line change
Expand Up @@ -2002,96 +2002,88 @@ class RequestOptions:
:attr:`falcon.asgi.App.req_options` for configuring certain
:class:`~.Request` and :class:`falcon.asgi.Request` behaviors,
respectively.
"""

Attributes:
keep_blank_qs_values (bool): Set to ``False`` to ignore query string
params that have missing or blank values (default ``True``).
For comma-separated values, this option also determines
whether or not empty elements in the parsed list are
retained.
auto_parse_form_urlencoded: Set to ``True`` in order to
automatically consume the request stream and merge the
results into the request's query string params when the
request's content type is
*application/x-www-form-urlencoded* (default ``False``).
Enabling this option for WSGI apps makes the form parameters
accessible via :attr:`~falcon.Request.params`,
:meth:`~falcon.Request.get_param`, etc.
Warning:
The `auto_parse_form_urlencoded` option is not supported for
ASGI apps, and is considered deprecated for WSGI apps as of
Falcon 3.0, in favor of accessing URL-encoded forms
through :attr:`~Request.media`.
See also: :ref:`access_urlencoded_form`
Warning:
When this option is enabled, the request's body
stream will be left at EOF. The original data is
not retained by the framework.
keep_black_qs_values: bool
"""Set to ``False`` to ignore query string params that have missing or blank
values (default ``True``).
Note:
The character encoding for fields, before
percent-encoding non-ASCII bytes, is assumed to be
UTF-8. The special `_charset_` field is ignored if
present.
For comma-separated values, this option also determines whether or not
empty elements in the parsed list are retained.
"""
auto_parse_form_urlencoded: bool
"""Set to ``True`` in order to automatically consume the request stream and merge
the results into the request's query string params when the request's content
type is ``application/x-www-form-urlencoded``` (default ``False``).
Falcon expects form-encoded request bodies to be
encoded according to the standard W3C algorithm (see
also http://goo.gl/6rlcux).
Enabling this option for WSGI apps makes the form parameters accessible via
:attr:`~falcon.Request.params`, :meth:`~falcon.Request.get_param`, etc.
auto_parse_qs_csv: Set to ``True`` to split query string values on
any non-percent-encoded commas (default ``False``).
Warning:
The `auto_parse_form_urlencoded` option is not supported for
ASGI apps, and is considered deprecated for WSGI apps as of
Falcon 3.0, in favor of accessing URL-encoded forms
through :attr:`~Request.media`.
When ``False``,
values containing commas are left as-is. In this mode, list items
are taken only from multiples of the same parameter name within the
query string (i.e. ``t=1,2,3&t=4`` becomes ``['1,2,3', '4']``).
See also: :ref:`access_urlencoded_form`
When `auto_parse_qs_csv` is set to ``True``, the query string value
is also split on non-percent-encoded commas and these items
are added to the final list (i.e. ``t=1,2,3&t=4,5``
becomes ``['1', '2', '3', '4', '5']``).
Warning:
When this option is enabled, the request's body
stream will be left at EOF. The original data is
not retained by the framework.
Warning:
Enabling this option will cause the framework to misinterpret
any JSON values that include literal (non-percent-encoded)
commas. If the query string may include JSON, you can
use JSON array syntax in lieu of CSV as a workaround.
strip_url_path_trailing_slash: Set to ``True`` in order to
strip the trailing slash, if present, at the end of the URL
path (default ``False``). When this option is enabled,
the URL path is normalized by stripping the trailing slash
character. This lets the application define a single route
to a resource for a path that may or may not end in a
forward slash. However, this behavior can be problematic in
certain cases, such as when working with authentication
schemes that employ URL-based signatures.
default_media_type (str): The default media-type used to
deserialize a request body, when the Content-Type header is
missing or ambiguous. This value is normally
set to the media type provided to the :class:`falcon.App` or
:class:`falcon.asgi.App` initializer; however, if created
independently, this will default to
:attr:`falcon.DEFAULT_MEDIA_TYPE`.
media_handlers (Handlers): A dict-like object for configuring the
media-types to handle. By default, handlers are provided for the
``application/json``, ``application/x-www-form-urlencoded`` and
``multipart/form-data`` media types.
Note:
The character encoding for fields, before
percent-encoding non-ASCII bytes, is assumed to be
UTF-8. The special `_charset_` field is ignored if
present.
Falcon expects form-encoded request bodies to be
encoded according to the standard W3C algorithm (see
also https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#application%2Fx-www-form-urlencoded-encoding-algorithm).
"""

keep_black_qs_values: bool
auto_parse_form_urlencoded: bool
auto_parse_qs_csv: bool
"""Set to ``True`` to split query string values on any non-percent-encoded
commas (default ``False``).
When ``False``, values containing commas are left as-is. In this mode, list items
are taken only from multiples of the same parameter name within the
query string (i.e. ``t=1,2,3&t=4`` becomes ``['1,2,3', '4']``).
When `auto_parse_qs_csv` is set to ``True``, the query string value is also
split on non-percent-encoded commas and these items are added to the final
list (i.e. ``t=1,2,3&t=4,5`` becomes ``['1', '2', '3', '4', '5']``).
Warning:
Enabling this option will cause the framework to misinterpret
any JSON values that include literal (non-percent-encoded)
commas. If the query string may include JSON, you can
use JSON array syntax in lieu of CSV as a workaround.
"""
strip_url_path_trailing_slash: bool
"""Set to ``True`` in order to strip the trailing slash, if present, at the
end of the URL path (default ``False``).
When this option is enabled, the URL path is normalized by stripping the
trailing slash character. This lets the application define a single route
to a resource for a path that may or may not end in a forward slash.
However, this behavior can be problematic in certain cases, such as when
working with authentication schemes that employ URL-based signatures.
"""
default_media_type: str
"""The default media-type used to deserialize a request body, when the
Content-Type header is missing or ambiguous.
This value is normally set to the media type provided to the :class:`falcon.App`
or :class:`falcon.asgi.App` initializer; however, if created independently,
this will default to :attr:`falcon.DEFAULT_MEDIA_TYPE`.
"""
media_handlers: Handlers
"""A dict-like object for configuring the media-types to handle.
By default, handlers are provided for the ``application/json``,
``application/x-www-form-urlencoded`` and ``multipart/form-data`` media types.
"""

__slots__ = (
'keep_blank_qs_values',
Expand Down
Loading

0 comments on commit a452a2d

Please sign in to comment.