Utilities#
This page describes miscellaneous utilities provided by Falcon.
URI#
URI utilities.
This module provides utility functions to parse, encode, decode, and otherwise manipulate a URI. These functions are not available directly in the falcon module, and so must be explicitly imported:
from falcon import uri
name, port = uri.parse_host('example.org:8080')
- falcon.uri.decode(encoded_uri: str, unquote_plus: bool = True) str [source]#
Decode percent-encoded characters in a URI or query string.
This function models the behavior of urllib.parse.unquote_plus, albeit in a faster, more straightforward manner.
- Parameters:
encoded_uri (str) – An encoded URI (full or partial).
- Keyword Arguments:
unquote_plus (bool) – Set to
False
to retain any plus (‘+’) characters in the given string, rather than converting them to spaces (defaultTrue
). Typically you should set this toFalse
when decoding any part of a URI other than the query string.- Returns:
A decoded URL. If the URL contains escaped non-ASCII characters, UTF-8 is assumed per RFC 3986.
- Return type:
- falcon.uri.encode(uri: str) str #
Encodes a full or relative URI according to RFC 3986.
RFC 3986 defines a set of “unreserved” characters as well as a set of “reserved” characters used as delimiters. This function escapes all other “disallowed” characters by percent-encoding them.
Note
This utility is faster in the average case than the similar quote function found in
urlib
. It also strives to be easier to use by assuming a sensible default of allowed characters.
- falcon.uri.encode_check_escaped(uri: str) str #
Encodes a full or relative URI according to RFC 3986.
RFC 3986 defines a set of “unreserved” characters as well as a set of “reserved” characters used as delimiters. This function escapes all other “disallowed” characters by percent-encoding them unless they appear to have been previously encoded. For example,
'%26'
will not be encoded again as it follows the format of an encoded value.Note
This utility is faster in the average case than the similar quote function found in
urlib
. It also strives to be easier to use by assuming a sensible default of allowed characters.
- falcon.uri.encode_value(uri: str) str #
Encodes a value string according to RFC 3986.
Disallowed characters are percent-encoded in a way that models
urllib.parse.quote(safe="~")
. However, the Falcon function is faster in the average case than the similar quote function found in urlib. It also strives to be easier to use by assuming a sensible default of allowed characters.All reserved characters are lumped together into a single set of “delimiters”, and everything in that set is escaped.
Note
RFC 3986 defines a set of “unreserved” characters as well as a set of “reserved” characters used as delimiters.
- falcon.uri.encode_value_check_escaped(uri: str) str #
Encodes a value string according to RFC 3986.
RFC 3986 defines a set of “unreserved” characters as well as a set of “reserved” characters used as delimiters. Disallowed characters are percent-encoded in a way that models
urllib.parse.quote(safe="~")
unless they appear to have been previously encoded. For example,'%26'
will not be encoded again as it follows the format of an encoded value.All reserved characters are lumped together into a single set of “delimiters”, and everything in that set is escaped.
Note
This utility is faster in the average case than the similar quote function found in
urlib
. It also strives to be easier to use by assuming a sensible default of allowed characters.
- falcon.uri.parse_host(host: str, default_port: int | None = None) Tuple[str, int | None] [source]#
Parse a canonical ‘host:port’ string into parts.
Parse a host string (which may or may not contain a port) into parts, taking into account that the string may contain either a domain name or an IP address. In the latter case, both IPv4 and IPv6 addresses are supported.
- Parameters:
host (str) – Host string to parse, optionally containing a port number.
- Keyword Arguments:
default_port (int) – Port number to return when the host string does not contain one (default
None
).- Returns:
A parsed (host, port) tuple from the given host string, with the port converted to an
int
. If the host string does not specify a port, default_port is used instead.- Return type:
- falcon.uri.parse_query_string(query_string: str, keep_blank: bool = False, csv: bool = False) Dict[str, str | List[str]] [source]#
Parse a query string into a dict.
Query string parameters are assumed to use standard form-encoding. Only parameters with values are returned. For example, given ‘foo=bar&flag’, this function would ignore ‘flag’ unless the keep_blank option is set.
Note
In addition to the standard HTML form-based method for specifying lists by repeating a given param multiple times, Falcon supports a more compact form in which the param may be given a single time but set to a
list
of comma-separated elements (e.g., ‘foo=a,b,c’). This comma-separated format can be enabled by setting the csv option (see below) toTrue
.When using this format, all commas uri-encoded will not be treated by Falcon as a delimiter. If the client wants to send a value as a list, it must not encode the commas with the values.
The two different ways of specifying lists may not be mixed in a single query string for the same parameter.
- Parameters:
query_string (str) – The query string to parse.
keep_blank (bool) – Set to
True
to return fields even if they do not have a value (defaultFalse
). For comma-separated values, this option also determines whether or not empty elements in the parsed list are retained.csv – Set to
True
in order to enable splitting query parameters on,
(defaultFalse
). Depending on the user agent, encoding lists as multiple occurrences of the same parameter might be preferable. In this case, keeping parse_qs_csv at its default value (False
) will cause the framework to treat commas as literal characters in each occurring parameter value.
- Returns:
A dictionary of (name, value) pairs, one per query parameter. Note that value may be a single
str
, or alist
ofstr
.- Return type:
- Raises:
TypeError – query_string was not a
str
.
Date and Time#
- falcon.http_now() str [source]#
Return the current UTC time as an IMF-fixdate.
- Returns:
The current UTC time as an IMF-fixdate, e.g., ‘Tue, 15 Nov 1994 12:45:26 GMT’.
- Return type:
- falcon.dt_to_http(dt: datetime) str [source]#
Convert a
datetime
instance to an HTTP date string.- Parameters:
dt (datetime) – A
datetime
instance to convert, assumed to be UTC.- Returns:
An RFC 1123 date string, e.g.: “Tue, 15 Nov 1994 12:45:26 GMT”.
- Return type:
- falcon.http_date_to_dt(http_date: str, obs_date: bool = False) datetime [source]#
Convert an HTTP date string to a datetime instance.
- Parameters:
http_date (str) – An RFC 1123 date string, e.g.: “Tue, 15 Nov 1994 12:45:26 GMT”.
- Keyword Arguments:
obs_date (bool) – Support obs-date formats according to RFC 7231, e.g.: “Sunday, 06-Nov-94 08:49:37 GMT” (default
False
).- Returns:
A UTC datetime instance corresponding to the given HTTP date.
- Return type:
datetime
- Raises:
ValueError – http_date doesn’t match any of the available time formats
ValueError – http_date doesn’t match allowed timezones
Changed in version 4.0: This function now returns timezone-aware
datetime
objects.
- class falcon.TimezoneGMT[source]#
GMT timezone class implementing the
datetime.tzinfo
interface.Deprecated since version 4.0:
TimezoneGMT
is deprecated, usedatetime.timezone.utc
instead. (This class will be removed in Falcon 5.0.)- dst(dt: datetime | None) timedelta [source]#
Return the daylight saving time (DST) adjustment.
- Parameters:
dt (datetime.datetime) – Ignored
- Returns:
DST adjustment for GMT, which is always 0.
- Return type:
- tzname(dt: datetime | None) str [source]#
Get the name of this timezone.
- Parameters:
dt (datetime.datetime) – Ignored
- Returns:
“GMT”
- Return type:
HTTP Status#
- falcon.http_status_to_code(status: HTTPStatus | int | bytes | str) int [source]#
Normalize an HTTP status to an integer code.
This function takes a member of
http.HTTPStatus
, an HTTP status line string or byte string (e.g.,'200 OK'
), or anint
and returns the corresponding integer code.An LRU is used to minimize lookup time.
- Parameters:
status – The status code or enum to normalize.
- Returns:
Integer code for the HTTP status (e.g., 200)
- Return type:
- falcon.code_to_http_status(status: int | HTTPStatus | bytes | str) str [source]#
Normalize an HTTP status to an HTTP status line string.
This function takes a member of
http.HTTPStatus
, anint
status code, an HTTP status line string or byte string (e.g.,'200 OK'
) and returns the corresponding HTTP status line string.An LRU is used to minimize lookup time.
Note
This function will not attempt to coerce a string status to an integer code, assuming the string already denotes an HTTP status line.
- Parameters:
status – The status code or enum to normalize.
- Returns:
- HTTP status line corresponding to the given code. A newline
is not included at the end of the string.
- Return type:
Media types#
- falcon.parse_header(line: str) Tuple[str, Dict[str, str]] [source]#
Parse a Content-type like header.
Return the main content-type and a dictionary of options.
- Parameters:
line – A header value to parse.
- Returns:
(the main content-type, dictionary of options).
- Return type:
Note
This function replaces an equivalent method previously available in the stdlib as
cgi.parse_header()
. It was removed from the stdlib in Python 3.13.Added in version 4.0.
- falcon.mediatypes.quality(media_type: str, header: str) float #
Get quality of the most specific matching media range.
Media-ranges are parsed from the provided header value according to RFC 9110, Section 12.5.1 (the
Accept
header).The provided media_type is matched against each of the parsed media ranges, and the fitness of each match is assessed as follows (in the decreasing priority list of criteria):
Do the main types (as in
type/subtype
) match?The types must either match exactly, or as wildcard (
*
). The matches involving a wildcard are prioritized lower.Do the subtypes (as in
type/subtype
) match?The subtypes must either match exactly, or as wildcard (
*
). The matches involving a wildcard are prioritized lower.Do the parameters match exactly?
If all the parameter names and values (if any) between the media range and media type match exactly, such match is prioritized higher than matches involving extraneous parameters on either side.
Note that if parameter names match, the corresponding values must also be equal, or the provided media type is considered not to match the media range in question at all.
The number of matching parameters.
Finally, if two or more best media range matches are equally fit according to all of the above criteria (1) through (4), the highest quality (i.e., the value of the
q
parameter) of these is returned.
Note
With the exception of evaluating the exact parameter match (3), the number of extraneous parameters (i.e. where the names are only present in the media type, or only in the media range) currently does not influence the described specificity sort order.
- Parameters:
media_type – The Internet media type to match against the provided HTTP
Accept
header value.header – The value of a header that conforms to the format of the HTTP
Accept
header.
- Returns:
Quality of the most specific media range matching the provided media_type. (If none matches, 0.0 is returned.)
Added in version 4.0.
- falcon.mediatypes.best_match(media_types: Iterable[str], header: str) str #
Choose media type with the highest
quality()
from a list of candidates.- Parameters:
media_types – An iterable over one or more Internet media types to match against the provided header value.
header – The value of a header that conforms to the format of the HTTP
Accept
header.
- Returns:
Best match from the supported candidates, or an empty string if the provided header value does not match any of the given types.
Added in version 4.0.
Async#
Aliases#
Falcon used to provide aliases for the below functions implemented in
asyncio
, with fallbacks for older versions of Python:
falcon.get_running_loop()
→asyncio.get_running_loop()
falcon.create_task(coro, *, name=None)
→asyncio.create_task()
However, as of Falcon 4.0+, these aliases are identical to their asyncio
counterparts on all supported Python versions. (They are only kept for
compatibility purposes.)
Simply use asyncio.get_running_loop()
or asyncio.create_task()
directly in new code.
Adapters#
These functions help traverse the barrier between sync and async code.
- async falcon.sync_to_async(func: Callable[[...], Any], *args: Any, **kwargs: Any) Callable[[...], Awaitable[Any]] [source]#
Schedule a synchronous callable on the default executor and await the result.
This helper makes it easier to call functions that can not be ported to use async natively (e.g., functions exported by a database library that does not yet support asyncio).
To execute blocking operations safely, without stalling the async loop, the wrapped callable is scheduled to run in the background, on a separate thread, when the wrapper is called.
The default executor for the running loop is used to schedule the synchronous callable.
Warning
This helper can only be used to execute thread-safe callables. If the callable is not thread-safe, it can be executed serially by first wrapping it with
wrap_sync_to_async()
, and then executing the wrapper directly.Warning
Calling a synchronous function safely from an asyncio event loop adds a fair amount of overhead to the function call, and should only be used when a native async library is not available for the operation you wish to perform.
- Parameters:
func (callable) – Function, method, or other callable to wrap
*args – All additional arguments are passed through to the callable.
- Keyword Arguments:
**kwargs – All keyword arguments are passed through to the callable.
- Returns:
An awaitable coroutine function that wraps the synchronous callable.
- Return type:
function
- falcon.wrap_sync_to_async(func: Callable[[...], Any], threadsafe: bool | None = None) Callable[[...], Any] [source]#
Wrap a callable in a coroutine that executes the callable in the background.
This helper makes it easier to call functions that can not be ported to use async natively (e.g., functions exported by a database library that does not yet support asyncio).
To execute blocking operations safely, without stalling the async loop, the wrapped callable is scheduled to run in the background, on a separate thread, when the wrapper is called.
Normally, the default executor for the running loop is used to schedule the synchronous callable. If the callable is not thread-safe, it can be scheduled serially in a global single-threaded executor.
Warning
Wrapping a synchronous function safely adds a fair amount of overhead to the function call, and should only be used when a native async library is not available for the operation you wish to perform.
- Parameters:
func (callable) – Function, method, or other callable to wrap
- Keyword Arguments:
threadsafe (bool) – Set to
False
when the callable is not thread-safe (defaultTrue
). When this argument isFalse
, the wrapped callable will be scheduled to run serially in a global single-threaded executor.- Returns:
An awaitable coroutine function that wraps the synchronous callable.
- Return type:
function
- falcon.wrap_sync_to_async_unsafe(func: Callable[[...], Any]) Callable[[...], Any] [source]#
Wrap a callable in a coroutine that executes the callable directly.
This helper makes it easier to use synchronous callables with ASGI apps. However, it is considered “unsafe” because it calls the wrapped function directly in the same thread as the asyncio loop. Generally, you should use
wrap_sync_to_async()
instead.Warning
This helper is only to be used for functions that do not perform any blocking I/O or lengthy CPU-bound operations, since the entire async loop will be blocked while the wrapped function is executed. For a safer, non-blocking alternative that runs the function in a thread pool executor, use
sync_to_async()
instead.- Parameters:
func (callable) – Function, method, or other callable to wrap
- Returns:
An awaitable coroutine function that wraps the synchronous callable.
- Return type:
function
- falcon.async_to_sync(coroutine: Callable[[...], Awaitable[Result]], *args: Any, **kwargs: Any) Result [source]#
Invoke a coroutine function from a synchronous caller.
This method can be used to invoke an asynchronous task from a synchronous context. The coroutine will be scheduled to run on the current event loop for the current OS thread. If an event loop is not already running, one will be created.
Warning
Executing async code in this manner is inefficient since it involves synchronization via threading primitives, and is intended primarily for testing, prototyping or compatibility purposes.
Note
On Python 3.11+, this function leverages a module-wide
asyncio.Runner
.- Parameters:
coroutine – A coroutine function to invoke.
*args – Additional args are passed through to the coroutine function.
- Keyword Arguments:
**kwargs – Additional args are passed through to the coroutine function.
- falcon.runs_sync(coroutine: Callable[[...], Awaitable[Result]]) Callable[[...], Result] [source]#
Transform a coroutine function into a synchronous method.
This is achieved by always invoking the decorated coroutine function via
async_to_sync()
.Warning
This decorator is very inefficient and should only be used for adapting asynchronous test functions for use with synchronous test runners such as
pytest
or theunittest
module.It will create an event loop for the current thread if one is not already running.
- Parameters:
coroutine – A coroutine function to masquerade as a synchronous one.
- Returns:
A synchronous function.
- Return type:
callable
Other#
- falcon.util.deprecated(instructions: str, is_property: bool = False, method_name: str | None = None) Callable[[Callable[[...], Any]], Any] [source]#
Flag a method as deprecated.
This function returns a decorator which can be used to mark deprecated functions. Applying this decorator will result in a warning being emitted when the function is used.
- Parameters:
instructions (str) – Specific guidance for the developer, e.g.: ‘Please migrate to add_proxy(…)’.
is_property (bool) – If the deprecated object is a property. It will omit the
(...)
from the generated documentation.method_name (str, optional) – Set to override the name of the deprecated function or property in the generated documentation (default
None
). This is useful when decorating an alias that carries the target’s__name__
.
- falcon.util.deprecated_args(*, allowed_positional: int, is_method: bool = True) Callable[[...], Callable[[...], Any]] [source]#
Flag a method call with positional args as deprecated.
- falcon.to_query_str(params: Mapping[str, Any] | None, comma_delimited_lists: bool = True, prefix: bool = True) str [source]#
Convert a dictionary of parameters to a query string.
- Parameters:
params (dict) – A dictionary of parameters, where each key is a parameter name, and each value is either a
str
or something that can be converted into astr
, or a list of such values. If alist
, the value will be converted to a comma-delimited string of values (e.g., ‘thing=1,2,3’).comma_delimited_lists (bool) – Set to
False
to encode list values by specifying multiple instances of the parameter (e.g., ‘thing=1&thing=2&thing=3’). Otherwise, parameters will be encoded as comma-separated values (e.g., ‘thing=1,2,3’). Defaults toTrue
.prefix (bool) – Set to
False
to exclude the ‘?’ prefix in the result string (defaultTrue
).
- Returns:
A URI query string, including the ‘?’ prefix (unless prefix is
False
), or an empty string if no params are given (thedict
is empty).- Return type:
- falcon.get_bound_method(obj: object, method_name: str) None | Callable[[...], Any] [source]#
Get a bound method of the given object by name.
- Parameters:
obj – Object on which to look up the method.
method_name – Name of the method to retrieve.
- Returns:
Bound method, or
None
if the method does not exist on the object.- Raises:
AttributeError – The method exists, but it isn’t bound (most likely a class was passed, rather than an instance of that class).
- falcon.secure_filename(filename: str) str [source]#
Sanitize the provided filename to contain only ASCII characters.
Only ASCII alphanumerals,
'.'
,'-'
and'_'
are allowed for maximum portability and safety wrt using this name as a filename on a regular file system. All other characters will be replaced with an underscore ('_'
).Note
The filename is normalized to the Unicode
NKFD
form prior to ASCII conversion in order to extract more alphanumerals where a decomposition is available. For instance:>>> secure_filename('Bold Digit 𝟏') 'Bold_Digit_1' >>> secure_filename('Ångström unit physics.pdf') 'A_ngstro_m_unit_physics.pdf'
- Parameters:
filename (str) – Arbitrary filename input from the request, such as a multipart form filename field.
- Returns:
The sanitized filename.
- Return type:
- Raises:
ValueError – the provided filename is an empty string.
- falcon.is_python_func(func: Callable | Any) bool [source]#
Determine if a function or method uses a standard Python type.
This helper can be used to check a function or method to determine if it uses a standard Python type, as opposed to an implementation-specific native extension type.
For example, because Cython functions are not standard Python functions,
is_python_func(f)
will returnFalse
when f is a reference to a cythonized function or method.- Parameters:
func – The function object to check.
- Returns:
True
if the function or method uses a standard Python type;False
otherwise.- Return type:
- class falcon.Context[source]#
Convenience class to hold contextual information in its attributes.
This class is used as the default
Request
andResponse
context type (seeRequest.context_type
andResponse.context_type
, respectively).In Falcon versions prior to 2.0, the default context type was
dict
. To ease the migration to attribute-based context object approach, this class also implements the mapping interface; that is, object attributes are linked to dictionary items, and vice versa. For instance:>>> context = falcon.Context() >>> context.cache_strategy = 'lru' >>> context.get('cache_strategy') 'lru' >>> 'cache_strategy' in context True
- class falcon.ETag[source]#
Convenience class to represent a parsed HTTP entity-tag.
This class is simply a subclass of
str
with a few helper methods and an extra attribute to indicate whether the entity-tag is weak or strong. The value of the string is equivalent to what RFC 7232 calls an “opaque-tag”, i.e. an entity-tag sans quotes and the weakness indicator.Note
Given that a weak entity-tag comparison can be performed by using the
==
operator (per the example below), only astrong_compare()
method is provided.Here is an example
on_get()
method that demonstrates how to use instances of this class:def on_get(self, req, resp): content_etag = self._get_content_etag() for etag in (req.if_none_match or []): if etag == '*' or etag == content_etag: resp.status = falcon.HTTP_304 return # -- snip -- resp.etag = content_etag resp.status = falcon.HTTP_200
(See also: RFC 7232)
- dumps() str [source]#
Serialize the ETag to a string suitable for use in a precondition header.
(See also: RFC 7232, Section 2.3)
- Returns:
An opaque quoted string, possibly prefixed by a weakness indicator
W/
.- Return type:
- classmethod loads(etag_str: str) ETag [source]#
Deserialize a single entity-tag string from a precondition header.
Note
This method is meant to be used only for parsing a single entity-tag. It can not be used to parse a comma-separated list of values.
(See also: RFC 7232, Section 2.3)
- strong_compare(other: ETag) bool [source]#
Perform a strong entity-tag comparison.
Two entity-tags are equivalent if both are not weak and their opaque-tags match character-by-character.
(See also: RFC 7232, Section 2.3.2)