Warning

These documents are OUTDATED as of 2023-12-31.

Please refer to the latest version of the documentation at sanic.dev.

πŸ“œ Changelog

πŸ”Ά Current release
πŸ”· In support release

Version 23.6.0 πŸ”Άοƒ

Features

  • #2670 Increase KEEP_ALIVE_TIMEOUT default to 120 seconds

  • #2716 Adding allow route overwrite option in blueprint

  • #2724 and #2792 Add a new exception signal for ALL exceptions raised anywhere in application

  • #2727 Add name prefixing to BP groups

  • #2754 Update request type on middleware types

  • #2770 Better exception message on startup time application induced import error

  • #2776 Set multiprocessing start method early

  • #2785 Add custom typing to config and ctx objects

  • #2790 Add request.client_ip

Bugfixes

  • #2728 Fix traversals for intended results

  • #2729 Handle case when headers argument of ResponseStream constructor is None

  • #2737 Fix type annotation for JSONREsponse default content type

  • #2740 Use Sanic’s serializer for JSON responses in the Inspector

  • #2760 Support for Request.get_current in ASGI mode

  • #2773 Alow Blueprint routes to explicitly define error_format

  • #2774 Resolve headers on different renderers

  • #2782 Resolve pypy compatibility issues

Deprecations and Removals

  • #2777 Remove Python 3.7 support

Developer infrastructure

  • #2766 Unpin setuptools version

  • #2779 Run keep alive tests in loop to get available port

Improved Documentation

  • #2741 Better documentation examples about running Sanic From that list, the items to highlight in the release notes:

Version 23.3.0

Features

  • #2545 Standardize init of exceptions for more consistent control of HTTP responses using exceptions

  • #2606 Decode headers as UTF-8 also in ASGI

  • #2646 Separate ASGI request and lifespan callables

  • #2659 Use FALLBACK_ERROR_FORMAT for handlers that return empty()

  • #2662 Add basic file browser (HTML page) and auto-index serving

  • #2667 Nicer traceback formatting (HTML page)

  • #2668 Smarter error page rendering format selection; more reliant upon header and β€œcommon sense” defaults

  • #2680 Check the status of socket before shutting down with SHUT_RDWR

  • #2687 Refresh Request.accept functionality to be more performant and spec-compliant

  • #2696 Add header accessors as properties

    Example-Field: Foo, Bar
    Example-Field: Baz
    
    request.headers.example_field == "Foo, Bar,Baz"
    
  • #2700 Simpler CLI targets

    $ sanic path.to.module:app          # global app instance
    $ sanic path.to.module:create_app   # factory pattern
    $ sanic ./path/to/directory/        # simple serve
    
  • #2701 API to define a number of workers in managed processes

  • #2704 Add convenience for dynamic changes to routing

  • #2706 Add convenience methods for cookie creation and deletion

    response = text("...")
    response.add_cookie("test", "It worked!", domain=".yummy-yummy-cookie.com")
    
  • #2707 Simplified parse_content_header escaping to be RFC-compliant and remove outdated FF hack

  • #2710 Stricter charset handling and escaping of request URLs

  • #2711 Consume body on DELETE by default

  • #2719 Allow password to be passed to TLS context

  • #2720 Skip middleware on RequestCancelled

  • #2721 Change access logging format to %s

  • #2722 Add CertLoader as application option for directly controlling SSLContext objects

  • #2725 Worker sync state tolerance on race condition

Bugfixes

  • #2651 ASGI websocket to pass thru bytes as is

  • #2697 Fix comparison between datetime aware and naive in file when using If-Modified-Since

Deprecations and Removals

  • #2666 Remove deprecated __blueprintname__ property

Improved Documentation

  • #2712 Improved example using 'https' to create the redirect

Version 22.12.0 πŸ”·οƒ

Current version

Features

  • #2569 Add JSONResponse class with some convenient methods when updating a response object

  • #2598 Change uvloop requirement to >=0.15.0

  • #2609 Add compatibility with websockets v11.0

  • #2610 Kill server early on worker error

    • Raise deadlock timeout to 30s

  • #2617 Scale number of running server workers

  • #2621 #2634 Send SIGKILL on subsequent ctrl+c to force worker exit

  • #2622 Add API to restart all workers from the multiplexer

  • #2624 Default to spawn for all subprocesses unless specifically set:

    from sanic import Sanic
    
    Sanic.start_method = "fork"
    
  • #2625 Filename normalisation of form-data/multipart file uploads

  • #2626 Move to HTTP Inspector:

    • Remote access to inspect running Sanic instances

    • TLS support for encrypted calls to Inspector

    • Authentication to Inspector with API key

    • Ability to extend Inspector with custom commands

  • #2632 Control order of restart operations

  • #2633 Move reload interval to class variable

  • #2636 Add priority to register_middleware method

  • #2639 Add unquote to add_route method

  • #2640 ASGI websockets to receive text or bytes

Bugfixes

  • #2607 Force socket shutdown before close to allow rebinding

  • #2590 Use actual StrEnum in Python 3.11+

  • #2615 Ensure middleware executes only once per request timeout

  • #2627 Crash ASGI application on lifespan failure

  • #2635 Resolve error with low-level server creation on Windows

Deprecations and Removals

  • #2608 #2630 Signal conditions and triggers saved on signal.extra

  • #2626 Move to HTTP Inspector

    • 🚨 BREAKING CHANGE: Moves the Inspector to a Sanic app from a simple TCP socket with a custom protocol

    • DEPRECATE: The --inspect* commands have been deprecated in favor of inspect ... commands

  • #2628 Replace deprecated distutils.strtobool

Developer infrastructure

  • #2612 Add CI testing for Python 3.11

Version 22.9.1

Features

  • #2585 Improved error message when no applications have been registered

Bugfixes

  • #2578 Add certificate loader for in process certificate creation

  • #2591 Do not use sentinel identity for spawn compatibility

  • #2592 Fix properties in nested blueprint groups

  • #2595 Introduce sleep interval on new worker reloader

Deprecations and Removals

Developer infrastructure

  • #2588 Markdown templates on issue forms

Improved Documentation

  • #2556 v22.9 documentation

  • #2582 Cleanup documentation on Windows support

Version 22.9.0

Features

  • #2445 Add custom loads function

  • #2490 Make WebsocketImplProtocol async iterable

  • #2499 Sanic Server WorkerManager refactor

  • #2506 Use pathlib for path resolution (for static file serving)

  • #2508 Use path.parts instead of match (for static file serving)

  • #2513 Better request cancel handling

  • #2516 Add request properties for HTTP method info:

    • request.is_safe

    • request.is_idempotent

    • request.is_cacheable

    • See MDN docs for more information about when these apply

  • #2522 Always show server location in ASGI

  • #2526 Cache control support for static files for returning 304 when appropriate

  • #2533 Refactor _static_request_handler

  • #2540 Add signals before and after handler execution

    • http.handler.before

    • http.handler.after

  • #2542 Add [redacted] to CLI :)

  • #2546 Add deprecation warning filter

  • #2550 Middleware priority and performance enhancements

Bugfixes

  • #2495 Prevent directory traversion with static files

  • #2515 Do not apply double slash to paths in certain static dirs in Blueprints

Deprecations and Removals

  • #2525 Warn on duplicate route names, will be prevented outright in v23.3

  • #2537 Raise warning and deprecation notice on duplicate exceptions, will be prevented outright in v23.3

Developer infrastructure

  • #2504 Cleanup test suite

  • #2505 Replace Unsupported Python Version Number from the Contributing Doc

  • #2530 Do not include tests folder in installed package resolver

Improved Documentation

Version 22.6.2

Bugfixes

  • #2522 Always show server location in ASGI

Version 22.6.1

Bugfixes

  • #2477 Sanic static directory fails when folder name ends with β€œ..”

Version 22.6.0

Features

  • #2378 Introduce HTTP/3 and autogeneration of TLS certificates in DEBUG mode

    • πŸ‘Ά EARLY RELEASE FEATURE: Serving Sanic over HTTP/3 is an early release feature. It does not yet fully cover the HTTP/3 spec, but instead aims for feature parity with Sanic’s existing HTTP/1.1 server. Websockets, WebTransport, push responses are examples of some features not yet implemented.

    • πŸ“¦ EXTRA REQUIREMENT: Not all HTTP clients are capable of interfacing with HTTP/3 servers. You may need to install a HTTP/3 capable client.

    • πŸ“¦ EXTRA REQUIREMENT: In order to use TLS autogeneration, you must install either mkcert or trustme.

  • #2416 Add message to task.cancel

  • #2420 Add exception aliases for more consistent naming with standard HTTP response types (BadRequest, MethodNotAllowed, RangeNotSatisfiable)

  • #2432 Expose ASGI scope as a property on the Request object

  • #2438 Easier access to websocket class for annotation: from sanic import Websocket

  • #2439 New API for reading form values with options: Request.get_form

  • #2445 Add custom loads function

  • #2447, #2486 Improved API to support setting cache control headers

  • #2453 Move verbosity filtering to logger

  • #2475 Expose getter for current request using Request.get_current()

Bugfixes

  • #2448 Fix to allow running with pythonw.exe or places where there is no sys.stdout

  • #2451 Trigger http.lifecycle.request signal in ASGI mode

  • #2455 Resolve typing of stacked route definitions

  • #2463 Properly catch websocket CancelledError in websocket handler in Python 3.7

Deprecations and Removals

  • #2487 v22.6 deprecations and changes

    1. Optional application registry

    2. Execution of custom handlers after some part of response was sent

    3. Configuring fallback handlers on the ErrorHandler

    4. Custom LOGO setting

    5. sanic.response.stream

    6. AsyncioServer.init

Developer infrastructure

  • #2449 Clean up black and isort config

  • #2479 Fix some flappy tests

Improved Documentation

  • #2461 Update example to match current application naming standards

  • #2466 Better type annotation for Extend

  • #2485 Improved help messages in CLI

Version 22.3.0

Features

  • #2347 API for multi-application server

    • 🚨 BREAKING CHANGE: The old sanic.worker.GunicornWorker has been removed. To run Sanic with gunicorn, you should use it thru uvicorn as described in their docs.

    • 🧁 SIDE EFFECT: Named background tasks are now supported, even in Python 3.7

  • #2357 Parse Authorization header as Request.credentials

  • #2361 Add config option to skip Touchup step in application startup

  • #2372 Updates to CLI help messaging

  • #2382 Downgrade warnings to backwater debug messages

  • #2396 Allow for multidict v0.6

  • #2401 Upgrade CLI catching for alternative application run types

  • #2402 Conditionally inject CLI arguments into factory

  • #2413 Add new start and stop event listeners to reloader process

  • #2414 Remove loop as required listener arg

  • #2415 Better exception for bad URL parsing

  • sanic-routing#47 Add a new extention parameter type: <file:ext>, <file:ext=jpg>, <file:ext=jpg|png|gif|svg>, <file=int:ext>, <file=int:ext=jpg|png|gif|svg>, <file=float:ext=tar.gz>

    • πŸ‘Ά BETA FEATURE: This feature will not work with path type matching, and is being released as a beta feature only.

  • sanic-routing#57 Change register_pattern to accept a str or Pattern

  • sanic-routing#58 Default matching on non-empty strings only, and new strorempty pattern type

    • 🚨 BREAKING CHANGE: Previously a route with a dynamic string parameter (/<foo> or /<foo:str>) would match on any string, including empty strings. It will now only match a non-empty string. To retain the old behavior, you should use the new parameter type: /<foo:strorempty>.

Bugfixes

  • #2373 Remove error_logger on websockets

  • #2381 Fix newly assigned None in task registry

  • sanic-routing#52 Add type casting to regex route matching

  • sanic-routing#60 Add requirements check on regex routes (this resolves, for example, multiple static directories with differing host values)

Deprecations and Removals

  • #2362 22.3 Deprecations and changes

    1. debug=True and --debug do NOT automatically run auto_reload

    2. Default error render is with plain text (browsers still get HTML by default because auto looks at headers)

    3. config is required for ErrorHandler.finalize

    4. ErrorHandler.lookup requires two positional args

    5. Unused websocket protocol args removed

  • #2344 Deprecate loading of lowercase environment variables

Developer infrastructure

Improved Documentation

  • #2350 Fix link in README for ASGI

  • #2398 Document middleware on_request and on_response

  • #2409 Add missing documentation for Request.respond

Miscellaneous

  • #2376 Fix typing for ListenerMixin.listener

  • #2383 Clear deprecation warning in asyncio.wait

  • #2387 Cleanup __slots__ implementations

  • #2390 Clear deprecation warning in asyncio.get_event_loop

Version 21.12.1 πŸ”·οƒ

Current LTS version

  • #2349 Only display MOTD on startup

  • #2354 Ignore name argument in Python 3.7

  • #2355 Add config.update support for all config values

Version 21.12.0 πŸ”Ήοƒ

Features

  • #2260 Allow early Blueprint registrations to still apply later added objects

  • #2262 Noisy exceptions - force logging of all exceptions

  • #2264 Optional uvloop by configuration

  • #2270 Vhost support using multiple TLS certificates

  • #2277 Change signal routing for increased consistency

    • BREAKING CHANGE: If you were manually routing signals there is a breaking change. The signal router’s get is no longer 100% determinative. There is now an additional step to loop thru the returned signals for proper matching on the requirements. If signals are being dispatched using app.dispatch or bp.dispatch, there is no change.

  • #2290 Add contextual exceptions

  • #2291 Increase join concat performance

  • #2295, #2316, #2331 Restructure of CLI and application state with new displays and more command parity with app.run

  • #2302 Add route context at definition time

  • #2304 Named tasks and new API for managing background tasks

  • #2307 On app auto-reload, provide insight of changed files

  • #2308 Auto extend application with Sanic Extensions if it is installed, and provide first class support for accessing the extensions

  • #2309 Builtin signals changed to Enum

  • #2313 Support additional config implementation use case

  • #2321 Refactor environment variable hydration logic

  • #2327 Prevent sending multiple or mixed responses on a single request

  • #2330 Custom type casting on environment variables

  • #2332 Make all deprecation notices consistent

  • #2335 Allow underscore to start instance names

Bugfixes

  • #2273 Replace assignation by typing for websocket_handshake

  • #2285 Fix IPv6 display in startup logs

  • #2299 Dispatch http.lifecyle.response from exception handler

Deprecations and Removals

  • #2306 Removal of deprecated items

    • Sanic and Blueprint may no longer have arbitrary properties attached to them

    • Sanic and Blueprint forced to have compliant names

      • alphanumeric + _ + -

      • must start with letter or _

    • load_env keyword argument of Sanic

    • sanic.exceptions.abort

    • sanic.views.CompositionView

    • sanic.response.StreamingHTTPResponse

  • #2320 Remove app instance from Config for error handler setting

Developer infrastructure

  • #2251 Change dev install command

  • #2286 Change codeclimate complexity threshold from 5 to 10

  • #2287 Update host test function names so they are not overwritten

  • #2292 Fail CI on error

  • #2311, #2324 Do not run tests for draft PRs

  • #2336 Remove paths from coverage checks

  • #2338 Cleanup ports on tests

Improved Documentation

Miscellaneous

Version 21.9.3

Rerelease of v21.9.2 with some cleanup

Version 21.9.2

  • #2268 Make HTTP connections start in IDLE stage, avoiding delays and error messages

  • #2310 More consistent config setting with post-FALLBACK_ERROR_FORMAT apply

Version 21.9.1

  • #2259 Allow non-conforming ErrorHandlers

Version 21.9.0

Features

  • #2158, #2248 Complete overhaul of I/O to websockets

  • #2160 Add new 17 signals into server and request lifecycles

  • #2162 Smarter auto fallback formatting upon exception

  • #2184 Introduce implementation for copying a Blueprint

  • #2200 Accept header parsing

  • #2207 Log remote address if available

  • #2209 Add convenience methods to BP groups

  • #2216 Add default messages to SanicExceptions

  • #2225 Type annotation convenience for annotated handlers with path parameters

  • #2236 Allow Falsey (but not-None) responses from route handlers

  • #2238 Add exception decorator to Blueprint Groups

  • #2244 Explicit static directive for serving file or dir (ex: static(..., resource_type="file"))

  • #2245 Close HTTP loop when connection task cancelled

Bugfixes

  • #2188 Fix the handling of the end of a chunked request

  • #2195 Resolve unexpected error handling on static requests

  • #2208 Make blueprint-based exceptions attach and trigger in a more intuitive manner

  • #2211 Fixed for handling exceptions of asgi app call

  • #2213 Fix bug where ws exceptions not being logged

  • #2231 Cleaner closing of tasks by using abort() in strategic places to avoid dangling sockets

  • #2247 Fix logging of auto-reload status in debug mode

  • #2246 Account for BP with exception handler but no routes

Developer infrastructure

  • #2194 HTTP unit tests with raw client

  • #2199 Switch to codeclimate

  • #2214 Try Reopening Windows Tests

  • #2229 Refactor HttpProtocol into a base class

  • #2230 Refactor server.py into multi-file module

Miscellaneous

  • #2173 Remove Duplicated Dependencies and PEP 517 Support

  • #2193, #2196, #2217 Type annotation changes