| toc_depth | 2 |
|---|
- Compare multidicts such as
FormDataandQueryParamsby key while keeping the order of values under a repeated key, soFormDatawith repeated uploads no longer raisesTypeError.QueryParams("a=1&a=2")andQueryParams("a=2&a=1")are no longer equal #3619. - Build URL-encoded form fields in the parser callbacks, lowering memory and CPU usage for forms with many fields #3724.
- Compare
Matchmembers by identity during routing #3665 and #3722.
- Deprecate
starlette.formparsers.FormMessage, which is no longer used #3724.
- Parse the last URL-encoded form field when the request stream ends without an empty chunk #3599.
- Keep path parameter values that look like another placeholder in
url_path_for()#3725. - Default omitted
http.response.startheaders inBaseHTTPMiddleware,GZipMiddlewareandSessionMiddlewareinstead of raisingKeyError#3721. - Clear the traceback of handled exceptions, so reused exception instances no longer keep per-request objects alive #3205.
- Strip only one pair of matching outer quotes from
Configenv file values #3720. - Strip
root_pathfromPATH_INFOonly at a path segment boundary inWSGIMiddleware#3718. - Report NaN and infinity correctly in
FloatConvertor.to_string()#3716. - Ignore
Rangeon requests other thanGETandHEADinFileResponse#3679.
- Stream
TestClientresponse bodies, soclient.stream()returns before the application finishes. Closing an unfinished streamed response now cancels the application #3491.
- Percent-encode
?,#,\and a leading//in the request path when buildingrequest.url, and\and a leading//inurl_path_for#3671. - Use the byte length for
Content-Lengthwhen the response body is a typed or multidimensionalmemoryview#3622. - Include
HEADin theAllowheader ofHTTPEndpoint405 responses whenGETis defined #3585. - Match host names case-insensitively in
Hostrouting andTrustedHostMiddleware#3542. - Preserve every existing
Varyheader inMutableHeaders.add_vary_header(), used byGZipMiddlewareandSessionMiddleware#3675.
This release drops Python 3.10 support and adds HTTP 103 Early Hints.
- Add
Request.send_early_hints()for HTTP 103 Early Hints through the ASGIhttp.response.early_hintextension #3435.
- Require Python 3.11 or later, dropping support for Python 3.10 #3592.
- Exclude native gRPC media types (
application/grpcandapplication/grpc+...) fromGZipMiddlewarecompression by default #3565. - Send
http.response.startimmediately inGZipMiddlewarefor responses with an existingContent-Encoding, status206, or an excluded content type, instead of waiting for the first body chunk #3631. - Resolve the multipart charset once per request instead of once per field #3618.
- Preserve response trailers through
GZipMiddleware#3565. - Stop
FileResponsetransfers when the client disconnects #3523. - Stop multipart range responses when the file ends before a range is complete, instead of looping forever #3583.
- Ignore
RangewhenIf-Rangecontains a weak ETag #3567. - Include
Allow: GET, HEADinStaticFiles405responses #3640. - Close
Request.stream()generators deterministically, avoiding "Exception ignored" errors with stackedBaseHTTPMiddleware#3628. - Add
Vary: CookiewhenSession.pop()removes an existing key #3186. - Emit
Max-Age=0on the session cookie whenSessionMiddlewareusesmax_age=0#3651. - Bracket IPv6 hostnames in
URL.replace()#3617.
This release adds experimental OpenTelemetry tracing and requires AnyIO 4.
!!! warning "OpenTelemetryMiddleware is experimental" Its API and emitted telemetry may change in minor releases without a deprecation period #3574.
- Add experimental
OpenTelemetryMiddlewarefor HTTP server spans, with URL exclusions and custom tracer providers #3438, #3463, and #3520. - Expose the matched route through
scope["route"]#3438. - Support the
QUERYHTTP method inHTTPEndpoint, CORS, and OpenAPI 3.2 schema generation #3489. - Capture HTTP response trailers in
TestClientand expose them throughresponse.extensions["http.response.trailers"]#3563. - Support partitioned cookies in
SessionMiddleware#3510. - Add
partitionedtoResponse.delete_cookie()on Python 3.14 and later #3376. - Support IPv6 hosts in
TrustedHostMiddlewareandTestClient#3471. - Support Python 3.15 #3508.
- Require
anyio>=4.0.0,<5, dropping support for AnyIO 3 #3512. - Raise
WebSocketDisconnected, aRuntimeErrorsubclass, for disconnected WebSocket operations #2767. - Accept
Collection[str]inCORSMiddlewareconfiguration annotations, including sets and frozensets #3518.
- Run background tasks only after the response is sent when using
BaseHTTPMiddleware#3476. - Return
400for invalid multipart parser input #3492. - Include
Vary: Originon all normal CORS responses and vary preflight responses by all request headers that affect them #3516 and #3517. - Handle malformed
Hostheaders and IPv6 authorities consistently across URL construction, host routing, and redirect middleware #3472. - Ignore
Rangeheaders whenFileResponsehas a status other than200, preserving its status and full body #3568. - Handle standalone
If-None-Match: *inStaticFiles#3201. - Reject WebSocket requests to
StaticFileswithout raising an assertion error #3532. - Persist session mutations made with
popitem()and|=#3436. - Handle empty and absent payloads in
WebSocketEndpoint.decode()#3372. - Implement
identityonSimpleUserandUnauthenticatedUser#3271. - Allow
HTTPExceptionto use non-standard status codes without an explicitdetail#3545. - Avoid deprecated AnyIO imports in
TestClientand add explicit imports inWSGIMiddlewarefor AnyIO 4.15 compatibility #3498 and #3501. - Offload debug traceback rendering to a worker thread in
ServerErrorMiddleware#2858.
- Add
max_body_sizetoStarletteand route classes #3431. - Expose
http.response.debuginformation via response extensions #3130.
- Add
exclude_content_typesparameter toGZipMiddleware#3418.
- Expand default excluded content types in
GZipMiddleware#3421.
- Flush GZip output for each streamed chunk #3419.
- Skip compression of partial responses in
GZipMiddleware#3420.
- Default
thread_minimum_sizeto 128 KiB inGZipResponder, keeping it usable without the new keyword argument #3415.
- Offload large GZip compression to a worker thread, keeping the event loop responsive.
GZipMiddlewareaccepts a newthread_minimum_sizeparameter (default 128 KiB) controlling the minimum body chunk size compressed in a thread #3410.
- Use
zlib.compressobjinstead ofGzipFileinGZipMiddleware, reducing memory usage during compression #3411. - Lazily allocate
GZipMiddlewarecompression resources, avoiding compressor allocation for responses that are never compressed #3407.
- Enforce
max_fieldsandmax_part_sizeinFormParser#3329. - Enforce
FormParserlimits in parser callbacks #3331.
- Build
request.urlfrom structured components #3326. - Clamp oversized suffix ranges in
FileResponse#3307. - Catch
OSErroralongsideMultiPartExceptionwhen closing temp files #3191. - Avoid collapsing exception groups raised from user code #2830.
- Use
removeprefixto strip the weakETagindicator inis_not_modified#3193. - Fix
IndexErrorinURL.replace()on a URL with no authority #3317. - Adjust
testclienttyping and warnings #3322.
- Use
httpx2for type checking in thetestclientmodule #3304. - Add assert error for
requires()when the request parameter is not aRequesttype #3298.
- Support httpx2 in the test client #3291.
- Use
"application/octet-stream"as theFileResponsemedia type fallback #3283.
- Only dispatch standard HTTP verbs in
HTTPEndpoint#3286. - Reject absolute paths in
StaticFiles.lookup_path#3287.
- Ignore malformed
Hostheader when constructingrequest.url#3279.
Starlette 1.0 is here!
After nearly eight years since its creation, Starlette has reached its first stable release. Thank you to everyone who tested the release candidate and reported issues.
You can read more on the blog post.
- Track session access and modification in
SessionMiddleware#3166.
- Handle websocket denial responses in
StreamingResponseandFileResponse#3189. - Use
bytearrayfor field accumulation inFormParser#3179. - Move
parser.finalize()inside try/except inMultiPartParser.parse()#3153.
We're ready! I'm thrilled to announce the first release candidate for Starlette 1.0.
Starlette was created in June 2018 by Tom Christie, and has been on ZeroVer for years. Today, it's downloaded almost 10 million times a day, serves as the foundation for FastAPI, and has inspired many other frameworks. In the age of AI, Starlette continues to play an important role as a dependency of the Python MCP SDK.
This release focuses on removing deprecated features that were marked for removal in 1.0.0, along with some last minute bug fixes. It's a release candidate, so we can gather feedback from the community before the final 1.0.0 release soon.
A huge thank you to all the contributors who have helped make Starlette what it is today. In particular, I'd like to recognize:
- Kim Christie - The original creator of Starlette, Uvicorn, and MkDocs, and the current maintainer of HTTPX. Kim's work helped lay the foundation for the modern async Python ecosystem.
- Adrian Garcia Badaracco - One of the smartest people I know, whom I have the pleasure of working with at Pydantic.
- Thomas Grainger - My async teacher, always ready to help with questions.
- Alex GrΓΆnholm - Another async mentor, always prompt to help with questions.
- Florimond Manca - Always present in the early days of both Starlette and Uvicorn, and helped a lot in the ecosystem.
- Amin Alaee - Contributed a lot with file-related PRs.
- SebastiΓ‘n RamΓrez - Maintains FastAPI upstream, and always in contact to help with upstream issues.
- Alex Oleshkevich - Helped a lot on templates and many discussions.
- abersheeran - My go-to person when I need help on many subjects.
I'd also like to thank my sponsors for their support. A special thanks to @tiangolo, @huggingface, and @elevenlabs for their generous sponsorship, and to all my other sponsors:
@roboflow, @ogabrielluiz, @SaboniAmine, @russbiggs, @BryceBeagle, @chdsbd, @TheR1D, @ddanier, @larsyngvelundin, @jpizquierdo, @alixlahuec, @nathanchapman, @devid8642, @comet-ml, @Evil0ctal, @msehnout, and @codingjoe.
- Remove
on_startupandon_shutdownparameters fromStarletteandRouter. Use thelifespanparameter instead #3117. - Remove
on_event()decorator fromStarletteandRouter. Use thelifespanparameter instead #3117. - Remove
add_event_handler()method fromStarletteandRouter. Use thelifespanparameter instead #3117. - Remove
startup()andshutdown()methods fromRouter#3117. - Remove
@app.route()decorator fromStarletteandRouter. UseRoutein theroutesparameter instead #3117. - Remove
@app.websocket_route()decorator fromStarletteandRouter. UseWebSocketRoutein theroutesparameter instead #3117. - Remove
@app.exception_handler()decorator fromStarlette. Useexception_handlersparameter instead #3117. - Remove
@app.middleware()decorator fromStarlette. Usemiddlewareparameter instead #3117. - Remove
iscoroutinefunction_or_partial()fromstarlette.routing#3117. - Remove
**env_optionsparameter fromJinja2Templates. Use a preconfiguredjinja2.Environmentvia theenvparameter instead #3118. - Remove deprecated
TemplateResponse(name, context)signature fromJinja2Templates. UseTemplateResponse(request, name, ...)instead #3118. - Remove deprecated
methodparameter fromFileResponse#3147.
- Add state generic to
WebSocket#3132.
- Include
bytesunit inContent-Rangeheader on 416 responses. - Handle null bytes in
StaticFilespath #3139. - Use sort-based merge for
Rangeheader parsing #3138. - Set
Content-Typeinstead ofContent-Rangeon multi-range responses #3142. - Use CRLF line endings in multipart byterange boundaries #3143.
- Avoid mutating
FileResponseheaders on range requests #3144. - Return explicit origin in CORS response when credentials are allowed #3137.
- Enable
autoescapeby default inJinja2Templates#3148.
jinja2must now be installed to importJinja2Templates. Previously it would only fail when instantiating the class #3118.
- Only use
typing_extensionsin older Python versions #3109.
In this release, State can be accessed using dictionary-style syntax for improved type
safety (#3036).
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager
from typing import TypedDict
import httpx
from starlette.applications import Starlette
from starlette.requests import Request
class State(TypedDict):
http_client: httpx.AsyncClient
@asynccontextmanager
async def lifespan(app: Starlette) -> AsyncIterator[State]:
async with httpx.AsyncClient() as client:
yield {"http_client": client}
async def homepage(request: Request[State]):
client = request.state["http_client"]
# If you run the below line with mypy or pyright, it will reveal the correct type.
reveal_type(client) # Revealed type is 'httpx.AsyncClient'See Accessing State for more details.
- Add
allow_private_networkinCORSMiddleware#3065.
- Increase warning stacklevel on
DeprecationWarningfor wsgi module #3082.
- Drop Python 3.9 support #3061.
This is the last release that supports Python 3.9, which will be dropped in the next minor release.
- Relax strictness on
Middlewaretype #3059.
- Ignore
if-modified-sinceheader ifif-none-matchis present inStaticFiles#3044.
This release fixes a security vulnerability in the parsing logic of the Range header in FileResponse.
You can view the full security advisory: GHSA-7f5h-v6xp-fcq8
- Optimize the HTTP ranges parsing logic 4ea6e22b489ec388d6004cfbca52dd5b147127c5
- Add
encodingparameter toConfigclass #2996. - Support multiple cookie headers in
Request.cookies#3029. - Use
Literaltype forWebSocketEndpointencoding values #3027.
- Do not pollute exception context in
Middlewarewhen usingBaseHTTPMiddleware#2976.
- Add official Python 3.14 support #3013.
- Use
asyncio.iscoroutinefunctionfor Python 3.12 and older #2984.
- Make
UploadFilecheck for future rollover #2962.
- Add support for ASGI
pathsendextension #2671. - Add
partitionedattribute toResponse.set_cookie#2501.
- Change
methodsparameter type fromlist[str]toCollection[str]#2903. - Replace
import typingbyfrom typing import ...in the whole codebase #2867.
- Mark
ExceptionMiddleware.http_exceptionas async to prevent thread creation #2922.
- Prevents reraising of exception from BaseHttpMiddleware #2911.
- Use correct index on backwards compatible logic in
TemplateResponse#2909.
- Allow relative directory path when
follow_symlinks=True#2896.
GZipMiddleware: Make sureVaryheader is always added if a response can be compressed #2865.
- Raise exception from background task on BaseHTTPMiddleware #2812.
GZipMiddleware: Don't compress on server sent events #2871.
MultiPartParser: Renamemax_file_sizetospool_max_size#2780.
- Add deprecated warning to
TestClient(timeout=...)#2840.
- Turn directory into string on
lookup_pathon commonpath comparison #2851.
- Make
create_memory_object_streamcompatible with old anyio versions once again, and bump anyio minimum version to 3.6.2 #2833.
- Close
MemoryObjectReceiveStreamleft unclosed upon exception inBaseHTTPMiddlewarechildren #2813. - Collect errors more reliably from the WebSocket logic on the
TestClient#2814.
- Use a pair of memory object streams instead of two queues on the
TestClient#2829.
- Drop Python 3.8 support #2823.
- Remove
ExceptionMiddlewareimport proxy fromstarlette.exceptionsmodule #2826. - Remove deprecated
WS_1004_NO_STATUS_RCVDandWS_1005_ABNORMAL_CLOSURE#2827.
- Remove deprecated
allow_redirectsargument fromTestClient#2808.
- Make UUID path parameter conversion more flexible #2806.
- Raise
ClientDisconnectonStreamingResponse#2732.
- Use ETag from headers when parsing If-Range in FileResponse #2761.
- Follow directory symlinks in
StaticFileswhenfollow_symlinks=True#2711. - Bump minimum
python-multipartversion to0.0.180ba8395. - Bump minimum
httpxversion to0.27.0#2773.
- Exclude the query parameters from the
scope[raw_path]on theTestClient#2716. - Replace
dictbyMappingonHTTPException.headers#2749. - Correct middleware argument passing and improve factory pattern #2752.
- Revert bump on
python-multipartonstarlette[full]extras #2737.
- Bump minimum
python-multipartversion to0.0.13#2734. - Change
python-multipartimport topython_multipart#2733.
- Allow to raise
HTTPExceptionbeforewebsocket.accept()#2725.
This release fixes a Denial of service (DoS) via multipart/form-data requests.
You can view the full security advisory: GHSA-f96h-pmfr-66vw
- Add
max_part_sizetoMultiPartParserto limit the size of parts inmultipart/form-datarequests fd038f3.
- Allow use of
request.url_forwhen only "app" scope is available #2672. - Fix internal type hints to support
python-multipart==0.0.12#2708.
- Avoid regex re-compilation in
responses.pyandschemas.py#2700. - Improve performance of
get_route_pathby removing regular expression usage #2701. - Consider
FileResponse.chunk_sizewhen handling multiple ranges #2703. - Use
token_hexfor generating multipart boundary strings #2702.
- Add support for HTTP Range to
FileResponse#2697.
- Close unclosed
MemoryObjectReceiveStreaminTestClient#2693.
- Schedule
BackgroundTasksfrom withinBaseHTTPMiddleware#2688. This behavior was removed in 0.38.3, and is now restored.
- Ensure accurate
root_pathremoval inget_route_pathfunction #2600.
- Support for Python 3.13 #2662.
- Don't poll for disconnects in
BaseHTTPMiddlewareviaStreamingResponse#2620.
- Not assume all routines have
__name__onrouting.get_name()#2648.
- Revert "Add support for ASGI pathsend extension" #2649.
- Allow use of
memoryviewinStreamingResponseandResponse#2576 and #2577. - Send 404 instead of 500 when filename requested is too long on
StaticFiles#2583.
- Fail fast on invalid
Jinja2Templateinstantiation parameters #2568. - Check endpoint handler is async only once #2536.
- Add proper synchronization to
WebSocketTestSession#2597.
- Add
bytesto_RequestDatatype #2510.
- Revert "Turn
scope["client"]toNoneonTestClient(#2377)" #2525. - Remove deprecated
appargument passed tohttpx.Clienton theTestClient#2526.
- Warn instead of raise for missing env file on
Config#2485.
- Support the WebSocket Denial Response ASGI extension #2041.
- Create
anyio.Eventon async context #2459.
- Check if "extensions" in scope before checking the extension #2438.
- Add support for ASGI
pathsendextension #2435. - Cancel
WebSocketTestSessionon close #2427. - Raise
WebSocketDisconnectwhenWebSocket.send()exceptsIOError#2425. - Raise
FileNotFoundErrorwhen theenv_fileparameter onConfigis not valid #2422.
- Stop using the deprecated "method" parameter in
FileResponseinside ofStaticFiles#2406. - Make
typing-extensionsoptional again #2409.
- Add
*argstoMiddlewareand improve its type hints #2381.
- Use
IterableinsteadIteratoroniterate_in_threadpool#2362.
- Handle
root_pathto keep compatibility with mounted ASGI applications and WSGI #2400. - Turn
scope["client"]toNoneonTestClient#2377.
- Deprecate
FileResponse(method=...)parameter #2366.
- Do not overwrite
"path"and"root_path"scope keys #2352. - Set
ensure_ascii=Falseonjson.dumps()forWebSocket.send_json()#2341.
- Revert mkdocs-material from 9.1.17 to 9.4.7 #2326.
- Inherit from
HTMLResponseinstead ofResponseon_TemplateResponse#2274. - Restore the
Response.rendertype annotation to its pre-0.31.0 state #2264.
- Fix import error when
exceptiongroupisn't available #2231. - Set
url_forglobal for custom Jinja environments #2230.
- Officially support Python 3.12 #2214.
- Support AnyIO 4.0 #2211.
- Strictly type annotate Starlette (strict mode on mypy) #2180.
- Don't group duplicated headers on a single string when using the
TestClient#2219.
- Drop Python 3.7 support #2178.
- Add
follow_redirectsparameter toTestClient#2207. - Add
__str__toHTTPExceptionandWebSocketException#2181. - Warn users when using
lifespantogether withon_startup/on_shutdown#2193. - Collect routes from
Hostto generate the OpenAPI schema #2183. - Add
requestargument toTemplateResponse#2191.
- Stop
body_streamin casemore_body=FalseonBaseHTTPMiddleware#2194.
- Reuse
Request's body buffer for call_next inBaseHTTPMiddleware#1692. - Move exception handling logic to
Route#2026.
- Add
envparameter toJinja2Templates, and deprecate**env_options#2159. - Add clear error message when
httpxis not installed #2177.
- Allow "name" argument on
templates url_for()#2127.
This release fixes a path traversal vulnerability in StaticFiles. You can view the full security advisory:
https://github.com/Kludex/starlette/security/advisories/GHSA-v5gw-mw7f-84px
- Minify JSON websocket data via
send_json#2128
- Replace
commonprefixbycommonpathonStaticFiles1797de4. - Convert ImportErrors into ModuleNotFoundError #2135.
- Correct the RuntimeError message content in websockets #2141.
- Fix typing of Lifespan to allow subclasses of Starlette #2077.
- Replace reference from Events to Lifespan on the mkdocs.yml #2072.
- Support lifespan state #2060, #2065 and #2064.
- Change
url_forsignature to return aURLinstance #1385.
- Allow "name" argument on
url_for()andurl_path_for()#2050.
- Deprecate
on_startupandon_shutdownevents #2070.
- Limit the number of fields and files when parsing
multipart/form-dataon theMultipartParser8c74c2c and #2036.
- Allow
StaticFilesto follow symlinks #1683. - Allow
Request.form()as a context manager #1903. - Add
sizeattribute toUploadFile#1405. - Add
env_prefixargument toConfig#1990. - Add template context processors #1904.
- Support
stranddatetimeonexpiresparameter on theResponse.set_cookiemethod #1908.
- Lazily build the middleware stack #2017.
- Make the
fileargument required onUploadFile#1413. - Use debug extension instead of custom response template extension #1991.
- Fix url parsing of ipv6 urls on
URL.replace#1965.
- Only stop receiving stream on
body_streamif body is empty on theBaseHTTPMiddleware#1940.
- Add
headersparameter to theTestClient#1966.
- Deprecate
StarletteandRouterdecorators #1897.
- Fix bug on
FloatConvertorregex #1973.
- Bypass
GZipMiddlewarewhen response includesContent-Encoding#1901.
- Remove unneeded
unquote()from query parameters on theTestClient#1953. - Make sure
MutableHeaders._listis actually alist#1917. - Import compatibility with the next version of
AnyIO#1936.
This release replaces the underlying HTTP client used on the TestClient (requests β‘οΈ httpx), and as those clients differ a bit on their API, your test suite will likely break. To make the migration smoother, you can use the bump-testclient tool.
- Replace
requestswithhttpxinTestClient#1376.
- Add
WebSocketExceptionand support for WebSocket exception handlers #1263. - Add
middlewareparameter toMountclass #1649. - Officially support Python 3.11 #1863.
- Implement
__repr__for route classes #1864.
- Fix bug on which
BackgroundTaskswere cancelled when usingBaseHTTPMiddlewareand client disconnected #1715.
- Remove converter from path when generating OpenAPI schema #1648.
- Revert "Allow
StaticFilesto follow symlinks" #1681.
- Improve detection of async callables #1444.
- Send 400 (Bad Request) when
boundaryis missing #1617. - Send 400 (Bad Request) when missing "name" field on
Content-Dispositionheader #1643. - Do not send empty data to
StreamingResponseonBaseHTTPMiddleware#1609. - Add
__bool__dunder forSecret#1625.
- Fix inference of
Route.namewhen created from methods #1553. - Avoid
TypeErroronwebsocket.disconnectwhen code isNone#1574.
- Deprecate
WS_1004_NO_STATUS_RCVDandWS_1005_ABNORMAL_CLOSUREin favor ofWS_1005_NO_STATUS_RCVDandWS_1006_ABNORMAL_CLOSURE, as the previous constants didn't match the WebSockets specs #1580.
- Error handler will always run, even if the error happens on a background task #761.
- Add
headersparameter toHTTPException#1435. - Internal responses with
405status code insert anAllowheader, as described by RFC 7231 #1436. - The
contentargument inJSONResponseis now required #1431. - Add custom URL convertor register #1437.
- Add content disposition type parameter to
FileResponse#1266. - Add next query param with original request URL in requires decorator #920.
- Add
raw_pathtoTestClientscope #1445. - Add union operators to
MutableHeaders#1240. - Display missing route details on debug page #1363.
- Change
anyiorequired version range to>=3.4.0,<5.0#1421 and #1460. - Add
typing-extensions>=3.10requirement - used only on lower versions than Python 3.10 #1475.
- Prevent
BaseHTTPMiddlewarefrom hiding errors ofStreamingResponseand mounted applications #1459. SessionMiddlewareuses an explicitpath=..., instead of defaulting to the ASGI 'root_path' #1512.Request.clientis now compliant with the ASGI specifications #1462.- Raise
KeyErrorat early stage for missing boundary #1349.
- Change default chunk size from 4Kb to 64Kb on
FileResponse#1345. - Add support for
functools.partialinWebSocketRoute#1356. - Add
StaticFilespackages with directory #1350. - Allow environment options in
Jinja2Templates#1401. - Allow HEAD method on
HttpEndpoint#1346. - Accept additional headers on
websocket.acceptmessage #1361 and #1422. - Add
reasontoWebSocketclose ASGI event #1417. - Add headers attribute to
UploadFile#1382. - Don't omit
Content-Lengthheader forContent-Length: 0cases #1395. - Don't set headers for responses with 1xx, 204 and 304 status code #1397.
SessionMiddleware.max_agenow acceptsNone, so cookie can last as long as the browser session #1387.
- Tweak
hashlib.md5()function onFileResponses ETag generation. The parameterusedforsecurityflag is set toFalse, if the flag is available on the system. This fixes an error raised on systems with FIPS enabled #1366 and #1410. - Fix
path_paramstype onurl_path_for()method i.e. turnstrintoAny#1341. Hostnow ignoresporton routing #1322.
- Fix
IndexErrorin authenticationrequireswhen wrapped function arguments are distributed between*argsand**kwargs#1335.
Response.delete_cookienow accepts the same parameters asResponse.set_cookie#1228.- Update the
Jinja2Templatesconstructor to allowPathLike#1292.
- Fix BadSignature exception handling in SessionMiddleware #1264.
- Change
HTTPConnection.__getitem__return type fromstrtotyping.Any#1118. - Change
ImmutableMultiDict.getlistreturn type fromtyping.List[str]totyping.List[typing.Any]#1235. - Handle
OSErrorexceptions onStaticFiles#1220. - Fix
StaticFiles404.html in HTML mode #1314. - Prevent anyio.ExceptionGroup in error views under a BaseHTTPMiddleware #1262.
- Remove GraphQL support #1198.
starlette.websockets.WebSocketinstances are now hashable and compare by identity #1039- A number of fixes related to running task groups in lifespan #1213, #1227
- The method
starlette.templates.Jinja2Templates.get_envwas removed #1218 - The ClassVar
starlette.testclient.TestClient.async_backendwas removed, the backend is now configured using constructor kwargs #1211 - Passing an Async Generator Function or a Generator Function to
starlette.routing.Router(lifespan=)is deprecated. You should wrap your lifespan in@contextlib.asynccontextmanager. #1227 #1110
This release includes major changes to the low-level asynchronous parts of Starlette. As a result, Starlette now depends on AnyIO and some minor API changes have occurred. Another significant change with this release is the deprecation of built-in GraphQL support.
- Starlette now supports Trio as an async runtime via AnyIO - #1157.
TestClient.websocket_connect()now must be used as a context manager.- Initial support for Python 3.10 - #1201.
- The compression level used in
GZipMiddlewareis now adjustable - #1128.
- Several fixes to
CORSMiddleware. See #1111, #1112, #1113, #1199. - Improved exception messages in the case of duplicated path parameter names - #1177.
RedirectResponsenow usesquoteinstead ofquote_plusencoding for theLocationheader to better match the behaviour in other frameworks such as Django - #1164.- Exception causes are now preserved in more cases - #1158.
- Session cookies now use the ASGI root path in the case of mounted applications - #1147.
- Fixed a cache invalidation bug when static files were deleted in certain circumstances - #1023.
- Improved memory usage of
BaseHTTPMiddlewarewhen handling large responses - #1012 fixed via #1157
- Built-in GraphQL support via the
GraphQLAppclass has been deprecated and will be removed in a future release. Please see #619. GraphQL is not supported on Python 3.10. - The
executorparameter toGraphQLAppwas removed. Useexecutor_classinstead. - The
workersparameter toWSGIMiddlewarewas removed. This hasn't had any effect since Starlette v0.6.3.
- Fixed
ServerErrorMiddlewarecompatibility with Python 3.9.1/3.8.7 when debug mode is enabled - #1132. - Fixed unclosed socket
ResourceWarnings when using theTestClientwith WebSocket endpoints - #1132. - Improved detection of
asyncendpoints wrapped infunctools.partialon Python 3.8+ - #1106.
UJSONResponsewas removed (this change was intended to be included in 0.14.0). Please see the documentation for how to implement responses using custom JSON serialization - #1074.
- Starlette now officially supports Python3.9.
- In
StreamingResponse, allow custom async iterator such as objects from classes implementing__aiter__. - Allow usage of
functools.partialasync handlers in Python versions 3.6 and 3.7. - Add 418 I'm A Teapot status code.
- Create tasks from handler coroutines before sending them to
asyncio.wait. - Use
format_exceptioninstead offormat_tbinServerErrorMiddleware'sdebugresponses. - Be more lenient with handler arguments when using the
requiresdecorator.
-
Revert
Queue(maxsize=1)fix forBaseHTTPMiddlewaremiddleware classes and streaming responses. -
The
StaticFilesconstructor now allowspathlib.Pathin addition to strings for itsdirectoryargument.
- Fix high memory usage when using
BaseHTTPMiddlewaremiddleware classes and streaming responses.
- Fix 404 errors with
StaticFiles.
- Add support for
Starlette(lifespan=...)functions. - More robust path-traversal check in StaticFiles app.
- Fix WSGI PATH_INFO encoding.
- RedirectResponse now accepts optional background parameter
- Allow path routes to contain regex meta characters
- Treat ASGI HTTP 'body' as an optional key.
- Don't use thread pooling for writing to in-memory upload files.
- Switch to promoting application configuration on init style everywhere. This means dropping the decorator style in favour of declarative routing tables and middleware definitions.
- Fix
request.url_for()for the Mount-within-a-Mount case.
- Fix
request.url_for()when an ASGIroot_pathis being used.
- Add
URL.include_query_params(**kwargs) - Add
URL.replace_query_params(**kwargs) - Add
URL.remove_query_params(param_names) request.stateproperly persisting across middleware.- Added
request.scopeinterface.
- Switch to ASGI 3.0.
- Fixes to CORS middleware.
- Add
StaticFiles(html=True)support. - Fix path quoting in redirect responses.
- Add
request.stateinterface, for storing arbitrary additional information. - Support disabling GraphiQL with
GraphQLApp(..., graphiql=False).
DatabaseMiddlewareis now dropped in favour ofdatabases- Templates are no longer configured on the application instance. Use
templates = Jinja2Templates(directory=...)andreturn templates.TemplateResponse('index.html', {"request": request}) - Schema generation is no longer attached to the application instance. Use
schemas = SchemaGenerator(...)andreturn schemas.OpenAPIResponse(request=request) LifespanMiddlewareis dropped in favor of router-based lifespan handling.- Application instances now accept a
routesargument,Starlette(routes=[...]) - Schema generation now includes mounted routes.
- Add
Lifespanrouting component.
- Ensure
templatingdoes not strictly requirejinja2to be installed.
- Templates are now configured independently from the application instance.
templates = Jinja2Templates(directory=...). Existing API remains in place, but is no longer documented, and will be deprecated in due course. See the template documentation for more details.
- Move to independent
databasespackage instead ofDatabaseMiddleware. Existing API remains in place, but is no longer documented, and will be deprecated in due course.
- Don't drop explicit port numbers on redirects from
HTTPSRedirectMiddleware.
- Add MySQL database support.
- Add host-based routing.
- WebSockets now default to sending/receiving JSON over text data frames. Use
.send_json(data, mode="binary")and.receive_json(mode="binary")for binary framing. GraphQLAppnow takes anexecutor_classargument, which should be used in preference to the existingexecutorargument. Resolves an issue with async executors being instantiated before the event loop was setup. Theexecutorargument is expected to be deprecated in the next median or major release.- Authentication and the
@requiresdecorator now support WebSocket endpoints. MultiDictandImmutableMultiDictclasses are available inuvicorn.datastructures.QueryParamsis now instantiated with standard dict-style*args, **kwargsarguments.
- Session cookies now include browser 'expires', in addition to the existing signed expiry.
request.form()now returns a multi-dict interface.- The query parameter multi-dict implementation now mirrors
dictmore correctly for the behavior of.keys(),.values(), and.items()when multiple same-key items occur. - Use
urlsplitthroughout in favor ofurlparse.
- Support
@requires(...)on class methods. - Apply URL escaping to form data.
- Support
HEADrequests automatically. - Add
await request.is_disconnected(). - Pass operationName to GraphQL executor.
- Add
TemplateResponse. - Add
CommaSeparatedStringsdatatype. - Add
BackgroundTasksfor multiple tasks. - Common subclass for
RequestandWebSocket, to eg. sharesessionfunctionality. - Expose remote address with
request.client.
- Add
request.database.executemany.
- Ensure that
AuthenticationMiddlewarehandles lifespan messages correctly.
- Add
AuthenticationMiddleware, and@requires()decorator.
- Support either
strorSecretforSessionMiddleware(secret_key=...).
- Add
config.environ. - Add
datastructures.Secret. - Add
datastructures.DatabaseURL.
- Add
config.Config(".env")
- Add optional database support.
- Add
requestto GraphQL context. - Hide any password component in
URL.__repr__.
- Handle startup/shutdown errors properly.
TestClientcan now be used as a context manager, instead ofLifespanContext.- Lifespan is now handled as middleware. Startup and Shutdown events are visible throughout the middleware stack.
- Better support for third-party API schema generators.
- Support chunked requests with TestClient.
- Cleanup asyncio tasks properly with WSGIMiddleware.
- Support using TestClient within endpoints, for service mocking.
- Session cookies are now set on the root path.
- Support URL convertors.
- Support HTTP 304 cache responses from
StaticFiles. - Resolve character escaping issue with form data.
- Default to empty body on responses.
- Add 'name' argument to
@app.route(). - Use 'Host' header for URL reconstruction.
- StaticFiles no longer reads the file for responses to
HEADrequests.
- Add a default templating configuration with Jinja2.
Allows the following:
app = Starlette(template_directory="templates")
@app.route('/')
async def homepage(request):
# `url_for` is available inside the template.
template = app.get_template('index.html')
content = template.render(request=request)
return HTMLResponse(content)- Add support for
@app.exception_handler(404). - Ensure handled exceptions are not seen as errors by the middleware stack.
- Add
max_age, and use timestamp-signed cookies. Defaults to two weeks.
- Ensure cookies are strictly HTTP correct.
- Check directory exists on instantiation.
- Add
starlette.concurrency.run_in_threadpool. Now handlescontextvarsupport.
- Add
name=support toapp.mount(). This allows eg:app.mount('/static', StaticFiles(directory='static'), name='static').
- Add support for
@app.middleware("http")decorator.
- Add "endpoint" to ASGI scope.
- Improve debug traceback information & styling.
- Support mounted URL lookups with "path=", eg.
url_for('static', path=...). - Support nested URL lookups, eg.
url_for('admin:user', username=...). - Add redirect slashes support.
- Add www redirect support.
- Add background task support to
FileResponseandStreamingResponse.
- Add
app.schema_generator = SchemaGenerator(...). - Add
app.schemaproperty. - Add
OpenAPIResponse(...).
- Drop
app.add_graphql_route("/", ...)in favor of more consistentapp.add_route("/", GraphQLApp(...)).
- Support routing to methods.
- Ensure
url_path_forworks with Mount('/{some_path_params}'). - Fix Router(default=) argument.
- Support repeated paths, like:
@app.route("/", methods=["GET"]),@app.route("/", methods=["POST"]) - Use the default ThreadPoolExecutor for all sync endpoints.
Added support for request.session, with SessionMiddleware.
Added support for BaseHTTPMiddleware, which provides a standard
request/response interface over a regular ASGI middleware.
This means you can write ASGI middleware while still working at a request/response level, rather than handling ASGI messages directly.
from starlette.applications import Starlette
from starlette.middleware.base import BaseHTTPMiddleware
class CustomMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request, call_next):
response = await call_next(request)
response.headers['Custom-Header'] = 'Example'
return response
app = Starlette()
app.add_middleware(CustomMiddleware)The biggest change in 0.6 is that endpoint signatures are no longer:
async def func(request: Request, **kwargs) -> ResponseInstead we just use:
async def func(request: Request) -> ResponseThe path parameters are available on the request as request.path_params.
This is different to most Python webframeworks, but I think it actually ends up being much more nicely consistent all the way through.
Request and WebSocketSession now support URL reversing with request.url_for(name, **path_params).
This method returns a fully qualified URL instance.
The URL instance is a string-like object.
Applications now support URL path reversing with app.url_path_for(name, **path_params).
This method returns a URL instance with the path and scheme set.
The URL instance is a string-like object, and will return only the path if coerced to a string.
Applications now support a .routes parameter, which returns a list of [Route|WebSocketRoute|Mount].
The low level components to Router now match the @app.route(), @app.websocket_route(), and app.mount() signatures.