Changelog for Falcon 4.0.0#
Summary#
We are happy to present Falcon 4.0, a new major version of the framework that
brings a couple of commonly requested features including support for matching
multiple path segments (using PathConverter), and
a fully typed codebase. (Please read more about typing in the notes below.)
The timeframe for Falcon 4.0 was challenging due to the need to balance our
high standards with the CPython 3.13 timeline. We aimed to deliver the main
development branch in this release, without resorting to another compatibility
micro update (as we did with Falcon 3.1.1-3.1.3). Following community feedback,
we also want to improve our overall release schedule by shipping smaller
increments more often.
To support this goal, we have made several tooling and testing improvements:
the build process for binary wheels has been simplified
using cibuildwheel, and our test suite now
only requires pytest as a hard dependency. Additionally, you can run
pytest against our tests from any directory. We hope that these changes
should also benefit packaging Falcon in Linux distributions.
As with every SemVer major release, we have removed a number of previously deprecated functions, classes, compatibility shims, as well as made other potentially breaking changes that we could not risk in a minor version. If you have been paying attention the deprecation warnings from the 3.x series, the impact should be minimal, but please do take a look at the list of breaking changes below.
This release would not have been possible without the numerous contributions from our community. This release alone comprises a number of pull requests submitted by a group of 30 talented individuals. What is more, we were particularly impressed by the high-quality discussions and code submissions during our EuroPython 2024 Sprint. Some notable sprint contributions include CHIPS support, and a new WebSocket Tutorial, among others. In fact, according to the statistics on GitHub, we are thrilled to report that the total number of Falcon contributors has now exceeded 200. We find it fascinating that our framework has become a collaborative effort involving so many individuals, and would like to thank everyone who has made this release possible!
Changes to Supported Platforms#
CPython 3.11 is now fully supported. (#2072)
CPython 3.12 is now fully supported. (#2196)
CPython 3.13 is now fully supported. (#2258)
End-of-life Python 3.5, 3.6 & 3.7 are no longer supported. (#2074, #2273)
End-of-life Python 3.8 is no longer actively supported, but the framework should still continue to install from the pure-Python wheel or source distribution, and function normally.
The Falcon 4.x series is guaranteed to support CPython 3.10 and PyPy3.10 (v7.3.16). This means that we may drop the support for Python 3.8 & 3.9 altogether in a later 4.x release, especially if we are faced with incompatible ecosystem changes in typing, Cython, etc.
Typing Support#
Type checking support was introduced in version 4.0. While most of the library is now typed, further type annotations may be added throughout the 4.x release cycle. To improve them, we may introduce changes to the typing that do not affect runtime behavior, but may surface new or different errors with type checkers.
Note
All undocumented type aliases coming from falcon._typing are considered
private to the framework itself, and not meant for annotating applications
using Falcon. To that end, it is advisable to only use classes from the
public interface, and public aliases from falcon.typing, e.g.:
class MyResource:
def on_get(self, req: falcon.Request, resp: falcon.Response) -> None:
resp.media = {'message': 'Hello, World!'}
If you still decide to reuse the private aliases anyway, they should
preferably be imported inside if TYPE_CHECKING: blocks in order
to avoid possible runtime errors after an update.
Also, make sure to let us know which essential aliases are
missing from the public interface!
Known typing limitations#
Falcon’s emphasis on flexibility and performance has presented certain
challenges when it comes to adding type annotations to the existing code base.
One notable limitation involves using custom Request and/or
Response types in callbacks that are passed back
to the framework, such as when adding an
error handler.
For instance, the following application might unexpectedly not pass type checking:
from typing import Any
from falcon import App, HTTPInternalServerError, Request, Response
class MyRequest(Request):
...
def handle_os_error(req: MyRequest, resp: Response, ex: Exception,
params: dict[str, Any]) -> None:
raise HTTPInternalServerError(title='OS error!') from ex
app = App(request_type=MyRequest)
app.add_error_handler(OSError, handle_os_error)
(Please also see the following GitHub issue: #2372.)
Important
This is only a typing limitation that has no effect outside of type
checking – the above app will run just fine!
Breaking Changes#
Falcon is no longer vendoring the python-mimeparse library; the relevant functionality has instead been reimplemented in the framework itself, fixing a handful of long-standing bugs in the new implementation.
If you use standalone python-mimeparse in your project, do not worry! We will continue to maintain it as a separate package under the Falconry umbrella (we took over about 3 years ago).
The following new behaviors are considered breaking changes:
Previously, the iterable passed to
req.client_prefershad to be sorted in the order of increasing desirability.best_match(), and by proxyclient_prefers(), now consider the provided media types to be sorted in the (more intuitive, we hope) order of decreasing desirability.Unlike
python-mimeparse, the new media type utilities consider media types with different values for the same parameters as non-matching.One theoretically possible scenario where this change can affect you is only installing a media handler for a content type with parameters; it then may not match media types with conflicting values (that used to match before Falcon 4.0). If this turns out to be the case, also install the same handler for the generic
type/subtypewithout parameters.
The new functions,
falcon.mediatypes.quality()andfalcon.mediatypes.best_match(), otherwise have the same signature as the corresponding methods frompython-mimeparse. (#864)A number of undocumented internal helpers were renamed to start with an underscore, indicating they are private methods intended to be used only by the framework itself:
falcon.request_helpers.header_property→falcon.request_helpers._header_propertyfalcon.request_helpers.parse_cookie_header→falcon.request_helpers._parse_cookie_headerfalcon.response_helpers.format_content_disposition→falcon.response_helpers._format_content_dispositionfalcon.response_helpers.format_etag_header→falcon.response_helpers._format_etag_headerfalcon.response_helpers.format_header_value_list→falcon.response_helpers._format_header_value_listfalcon.response_helpers.format_range→falcon.response_helpers._format_rangefalcon.response_helpers.header_property→falcon.response_helpers._header_propertyfalcon.response_helpers.is_ascii_encodable→falcon.response_helpers._is_ascii_encodable
If you were relying on these internal helpers, you can either copy the implementation into your codebase, or switch to the underscored variants. (Needless to say, though, we strongly recommend against referencing private methods, as we provide no SemVer guarantees for them.) (#1457)
A number of previously deprecated methods, attributes and classes have now been removed:
In Falcon 3.0, the use of positional arguments was deprecated for the optional initializer parameters of
falcon.HTTPErrorand its subclasses.We have now redefined these optional arguments as keyword-only, so passing them as positional arguments will result in a
TypeError:>>> import falcon >>> falcon.HTTPForbidden('AccessDenied') Traceback (most recent call last): <...> TypeError: HTTPForbidden.__init__() takes 1 positional argument but 2 were given >>> falcon.HTTPForbidden('AccessDenied', 'No write access') Traceback (most recent call last): <...> TypeError: HTTPForbidden.__init__() takes 1 positional argument but 3 were given
Instead, simply pass these parameters as keyword arguments:
>>> import falcon >>> falcon.HTTPForbidden(title='AccessDenied') <HTTPForbidden: 403 Forbidden> >>> falcon.HTTPForbidden(title='AccessDenied', description='No write access') <HTTPForbidden: 403 Forbidden>
The
falcon-print-routescommand-line utility is no longer supported;falcon-inspect-appis a direct replacement.falcon.stream.BoundedStreamis no longer re-imported viafalcon.request_helpers. If needed, import it directly asfalcon.stream.BoundedStream.A deprecated alias of
falcon.stream.BoundedStream,falcon.stream.Body, was removed. Usefalcon.stream.BoundedStreaminstead.A deprecated utility function,
falcon.get_http_status(), was removed. Please usefalcon.code_to_http_status()instead.A deprecated routing utility,
compile_uri_template(), was removed. This function was only employed in the early versions of the framework, and is expected to have been fully supplanted by theCompiledRouter. In a pinch, you can simply copy its implementation from the Falcon 3.x source tree into your application.The deprecated
Response.add_link()method was removed; please useResponse.append_linkinstead.The deprecated
has_representation()method forHTTPErrorwas removed, along with theNoRepresentationandOptionalRepresentationclasses.An undocumented, deprecated public method
find_by_media_type()ofmedia.Handlerswas removed. Apart from configuring handlers for Internet media types, the rest ofHandlersis only meant to be used internally by the framework (unless documented otherwise).Previously, the
jsonmodule could be imported viafalcon.util. This deprecated alias was removed; please importjsondirectly from thestandard library, or another third-party JSON library of choice.
We decided, on the other hand, to keep the deprecated
falcon.APIalias until Falcon 5.0. (#1853)Previously, it was possible to create an
Appwith thecors_enableoption, and add additionalCORSMiddleware, leading to unexpected behavior and dysfunctional CORS. This combination now explicitly results in aValueError. (#1977)The default value of the
csvparameter inparse_query_string()was changed toFalse, matching the default behavior of other parts of the framework (such asreq.params, the test client, etc). If the old behavior fits your use case better, pass thecsv=Truekeyword argument explicitly. (#1999)The deprecated
api_helperswas removed in favor of theapp_helpersmodule. In addition, the deprecatedbodyattributes of theResponse,asgi.Response, andHTTPStatusclasses were removed. (#2090)The function
falcon.http_date_to_dt()now validates HTTP dates to have the correct timezone set. It now also returns timezone-awaredatetimeobjects. As a consequence of this change, the return value offalcon.Request.get_header_as_datetime()(including the derived propertiesdate,if_modified_since,if_unmodified_since, andfalcon.testing.Cookie.expires) has also changed to timezone-aware.Furthermore, the default value of the format_string parameter in
falcon.Request.get_param_as_datetime()andfalcon.routing.DateTimeConverterhas also been updated to use a timezone-aware form. (#2182)setup.cfgwas dropped in favor of consolidating all static project configuration inpyproject.toml(setup.pyis still needed for programmatic control of the build process). While this change should not impact the framework’s end-users directly, somesetuptools-based legacy workflows (such as the obsoletesetup.py test) will no longer work. (#2314)The
is_asynckeyword argument was removed fromvalidate(), as well as the hooksbefore()andafter(), since it represented a niche use case that is even less relevant with the recent advances in the ecosystem: Cython 3.0+ will now correctly mark cythonizedasync deffunctions as coroutines, and pure-Python factory functions that return a coroutine can now be marked as such usinginspect.markcoroutinefunction()(Python 3.12+ is required). (#2343)
New & Improved#
A new keyword argument, link_extension, was added to
falcon.Response.append_link()as specified in RFC 8288, Section 3.4.2. (#228)A new
pathconvertercapable of matching segments that include/was added. (#648)The new implementation of media type utilities (Falcon was using the
python-mimeparselibrary before) now always favors the exact media type match, if one is available. (#1367)Type annotations have been added to Falcon’s public interface to the package itself in order to better support Mypy (or other type checkers) users without having to install any third-party typeshed packages. (#1947)
Similar to the existing
IntConverter, a newFloatConverterhas been added, allowing to convert path segments tofloat. (#2022)The default error serializer will now use the response media handlers to better negotiate the response content type with the client. The implementation still defaults to JSON if the client does not indicate any preference. (#2023)
WebSocketnow supports providing a reason for closing the socket, either directly viaclose()or by configuringdefault_close_reasons. (#2025)An informative representation was added to
testing.Resultfor easier development and interpretation of failed tests. The form of__repr__is as follows:Result<{status_code} {content-type header} {content}>, where the content part will reflect up to 40 bytes of the result’s content. (#2044)A new method
falcon.Request.get_header_as_int()was implemented. (#2060)A new property,
headers_lower, was added to provide a unified, self-documenting way to get a copy of all request headers with lowercase names to facilitate case-insensitive matching. This is especially useful for middleware components that need to be compatible with both WSGI and ASGI.headers_lowerwas added in lieu of introducing a breaking change to the WSGIheadersproperty that returns uppercase header names from the WSGIenvirondictionary. (#2063)In Python 3.13, the
cgimodule is removed entirely from the stdlib, including itsparse_header()method. Falcon addresses the issue by shipping an own implementation;falcon.parse_header()can also be used in your projects affected by the removal. (#2066)A new
status_codeattribute was added to thefalcon.Response,falcon.asgi.Response,HTTPStatus, andHTTPErrorclasses. (#2108)Following the recommendation from RFC 9239, the MEDIA_JS constant has been updated to
text/javascript. Furthermore, this and other media type constants are now preferred to the stdlib’smimetypesfor the initialization ofstatic_media_types. (#2110)A new keyword argument, samesite, was added to
unset_cookie()that allows to override the defaultLaxsetting of SameSite on the unset cookie. (#2124)A new keyword argument, partitioned, was added to
set_cookie()to opt a cookie into partitioned storage, with a separate cookie jar per each top-level site. (See also CHIPS for a more detailed description of this web technology.) (#2213)The class
falcon.HTTPPayloadTooLargewas renamed tofalcon.HTTPContentTooLarge, together with the accompanying HTTP status code update, in order to reflect the newest HTTP semantics as per RFC 9110, Section 15.5.14. (The old class name remains available as a deprecated compatibility alias.)In addition, one new status code constant was added:
falcon.HTTP_421(also available asfalcon.HTTP_MISDIRECTED_REQUEST) in accordance with RFC 9110, Section 15.5.20. (#2276)The
CORSMiddlewarenow properly handles the missingAllowheader case, by denying the preflight CORS request. The static file route has been updated to properly support CORS preflight, by allowingGETrequests. (#2325)Added
falcon.testing.Result.content_typeandfalcon.testing.StreamedResult.content_typeas a utility accessor for theContent-Typeheader. (#2349)A new flag,
xml_error_serialization, has been added toResponseOptionsthat can be used to disable automatic XML serialization ofHTTPErrorwhen using the default error serializer (and the client prefers it).This new flag currently defaults to
True, preserving the same behavior as the previous Falcon versions. Falcon 5.0 will either change the default toFalse, or remove the automatic XML error serialization altogether. If you wish to retain support for XML serialization in the default error serializer, you should add a response media handler for XML.In accordance with this change, the
falcon.HTTPError.to_xml()method was deprecated. (#2355)
Fixed#
The web servers used for tests are now run through
sys.executablein order to ensure that they respect the virtualenv in which tests are being run. (#2047)Previously, importing
TestCaseas a top-level attribute in a test module could makepytesterroneously attempt to collect its methods as test cases. This has now been prevented by adding a__test__attribute (set toFalse) to theTestCaseclass. (#2147)Falcon will now raise an instance of
WebSocketDisconnectedfrom theOSErrorthat the ASGI server signals in the case of a disconnected client (as per the ASGI HTTP & WebSocket protocol version2.4). It is worth noting though that Falcon’s built-in receive buffer normally detects thewebsocket.disconnectevent itself prior the potentially failing attempt tosend().Disabling this built-in receive buffer (by setting
max_receive_queueto0) was also found to interfere with receiving ASGI WebSocket messages in an unexpected way. The issue has been fixed so that setting this option to0now properly bypasses the buffer altogether, and extensive test coverage has been added for validating this scenario. (#2292)Customizing
MultipartParseOptions.media_handlerscould previously lead to unintentionally modifying a shared class variable. This has been fixed, and themedia_handlersattribute is now initialized to a fresh copy of handlers for every instance ofMultipartParseOptions. To that end, a propercopy()method has been implemented for the mediaHandlersclass. (#2293)Falcon’s multipart form parser no longer requires a CRLF (
'\r\n') after the closing--delimiter. Although it is a common convention (followed by the absolute majority of HTTP clients and web browsers) to include a trailing CRLF, the popular Undici client (used as Node’s defaultfetchimplementation) omits it at the time of this writing. (The next version of Undici will adhere to the convention.) (#2364)
Misc#
The utility functions
create_task()andget_running_loop()are now deprecated in favor of their standard library counterparts,asyncio.create_task()andasyncio.get_running_loop(). (#2253)The
falcon.TimezoneGMTclass was deprecated. Use the UTC timezone (datetime.timezone.utc) from the standard library instead. (#2301)
Contributors to this Release#
Many thanks to all of our talented and stylish contributors for this release!