Warning

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

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

Application

sanic.app

class sanic.app.Sanic(name: str, config: None = None, ctx: None = None, router: Router | None = None, signal_router: SignalRouter | None = None, error_handler: ErrorHandler | None = None, env_prefix: str | None = SANIC_PREFIX, request_class: Type[Request] | None = None, strict_slashes: bool = False, log_config: Dict[str, Any] | None = None, configure_logging: bool = True, dumps: Callable[[...], AnyStr] | None = None, loads: Callable[[...], Any] | None = None, inspector: bool = False, inspector_class: Type[Inspector] | None = None, certloader_class: Type[CertLoader] | None = None)
class sanic.app.Sanic(name: str, config: config_type | None = None, ctx: None = None, router: Router | None = None, signal_router: SignalRouter | None = None, error_handler: ErrorHandler | None = None, env_prefix: str | None = SANIC_PREFIX, request_class: Type[Request] | None = None, strict_slashes: bool = False, log_config: Dict[str, Any] | None = None, configure_logging: bool = True, dumps: Callable[[...], AnyStr] | None = None, loads: Callable[[...], Any] | None = None, inspector: bool = False, inspector_class: Type[Inspector] | None = None, certloader_class: Type[CertLoader] | None = None)
class sanic.app.Sanic(name: str, config: None = None, ctx: ctx_type | None = None, router: Router | None = None, signal_router: SignalRouter | None = None, error_handler: ErrorHandler | None = None, env_prefix: str | None = SANIC_PREFIX, request_class: Type[Request] | None = None, strict_slashes: bool = False, log_config: Dict[str, Any] | None = None, configure_logging: bool = True, dumps: Callable[[...], AnyStr] | None = None, loads: Callable[[...], Any] | None = None, inspector: bool = False, inspector_class: Type[Inspector] | None = None, certloader_class: Type[CertLoader] | None = None)
class sanic.app.Sanic(name: str, config: config_type | None = None, ctx: ctx_type | None = None, router: Router | None = None, signal_router: SignalRouter | None = None, error_handler: ErrorHandler | None = None, env_prefix: str | None = SANIC_PREFIX, request_class: Type[Request] | None = None, strict_slashes: bool = False, log_config: Dict[str, Any] | None = None, configure_logging: bool = True, dumps: Callable[[...], AnyStr] | None = None, loads: Callable[[...], Any] | None = None, inspector: bool = False, inspector_class: Type[Inspector] | None = None, certloader_class: Type[CertLoader] | None = None)

Bases: Generic[config_type, ctx_type], StaticHandleMixin, BaseSanic, StartupMixin

The main application instance

You will create an instance of this class and use it to register routes, listeners, middleware, blueprints, error handlers, etc.

By convention, it is often called app. It must be named using the name parameter and is roughly constrained to the same restrictions as a Python module name, however, it can contain hyphens (-).

`python # will cause an error because it contains spaces Sanic("This is not legal") `

`python # this is legal Sanic("Hyphens-are-legal_or_also_underscores") `

Args:
name (str): The name of the application. Must be a valid

Python module name (including hyphens).

config (Optional[config_type]): The configuration to use for

the application. Defaults to None.

ctx (Optional[ctx_type]): The context to use for the

application. Defaults to None.

router (Optional[Router]): The router to use for the

application. Defaults to None.

signal_router (Optional[SignalRouter]): The signal router to

use for the application. Defaults to None.

error_handler (Optional[ErrorHandler]): The error handler to

use for the application. Defaults to None.

env_prefix (Optional[str]): The prefix to use for environment

variables. Defaults to SANIC_.

request_class (Optional[Type[Request]]): The request class to

use for the application. Defaults to Request.

strict_slashes (bool): Whether to enforce strict slashes.

Defaults to False.

log_config (Optional[Dict[str, Any]]): The logging configuration

to use for the application. Defaults to None.

configure_logging (bool): Whether to configure logging.

Defaults to True.

dumps (Optional[Callable[…, AnyStr]]): The function to use

for serializing JSON. Defaults to None.

loads (Optional[Callable[…, Any]]): The function to use

for deserializing JSON. Defaults to None.

inspector (bool): Whether to enable the inspector. Defaults

to False.

inspector_class (Optional[Type[Inspector]]): The inspector

class to use for the application. Defaults to None.

certloader_class (Optional[Type[CertLoader]]): The certloader

class to use for the application. Defaults to None.

ack()

Shorthand to send an ack message to the Server Manager.

In general, this should usually not need to be called manually. It is used to tell the Manager that a process is operational and ready to begin operation.

Return type:

None

add_route(handler, uri, methods=frozenset({'GET'}), host=None, strict_slashes=None, version=None, name=None, stream=False, version_prefix='/v', error_format=None, unquote=False, **ctx_kwargs)

A helper method to register class-based view or functions as a handler to the application url routes.

Args:

handler (RouteHandler): Function or class-based view used as a route handler. uri (str): Path of the URL. methods (Iterable[str]): List or tuple of methods allowed; these are overridden if using an HTTPMethodView. host (Optional[Union[str, List[str]]]): Hostname or hostnames to match for this route. strict_slashes (Optional[bool]): If set, a route’s slashes will be strict. E.g. /foo will not match /foo/. version (Optional[Union[int, str, float]]): Version of the API for this route. name (Optional[str]): User-defined route name for url_for. stream (bool): Boolean specifying if the handler is a stream handler. version_prefix (str): URL path that should be before the version value; default: /v. error_format (Optional[str]): Custom error format string. unquote (bool): Boolean specifying if the handler requires unquoting. ctx_kwargs (Any): Keyword arguments that begin with a ctx_* prefix will be appended to the route context (route.ctx). See below for examples.

Returns:

RouteHandler: The route handler.

Examples:

```python from sanic import Sanic, text

app = Sanic(β€œtest”)

async def handler(request):

return text(β€œOK”)

app.add_route(handler, β€œ/test”, methods=[β€œGET”, β€œPOST”]) ```

You can use ctx_kwargs to add custom context to the route. This can often be useful when wanting to add metadata to a route that can be used by other parts of the application (like middleware).

```python from sanic import Sanic, text

app = Sanic(β€œtest”)

async def handler(request):

return text(β€œOK”)

async def custom_middleware(request):
if request.route.ctx.monitor:

do_some_monitoring()

app.add_route(handler, β€œ/test”, methods=[β€œGET”, β€œPOST”], ctx_monitor=True) app.register_middleware(custom_middleware)

Parameters:
  • handler (Callable[[...], Coroutine[Any, Any, HTTPResponse | None]]) –

  • uri (str) –

  • methods (Iterable[str]) –

  • host (str | List[str] | None) –

  • strict_slashes (bool | None) –

  • version (int | str | float | None) –

  • name (str | None) –

  • stream (bool) –

  • version_prefix (str) –

  • error_format (str | None) –

  • unquote (bool) –

  • ctx_kwargs (Any) –

Return type:

Callable[[…], Coroutine[Any, Any, HTTPResponse | None]]

add_signal(handler, event, condition=None, exclusive=True)

Registers a signal handler for a specific event.

Args:
handler (Optional[Callable[…, Any]]): The function to be called

when the event occurs. Defaults to a noop if not provided.

event (str): The name of the event to listen for. condition (Optional[Dict[str, Any]]): Optional condition to filter

the event triggering. Defaults to None.

exclusive (bool): Whether or not the handler is exclusive. When

True, the signal can only be dispatched when the condition has been met. This is inapplicable to blueprint signals, which are **ALWAYS* non-exclusive.* Defaults to True.

Returns:

Callable[…, Any]: The handler that was registered.

Parameters:
  • handler (Callable[[...], Any] | None) –

  • event (str | Enum) –

  • condition (Dict[str, Any] | None) –

  • exclusive (bool) –

Return type:

Callable[[…], Any]

add_task(task, *, name=None, register=True)

Schedule a task to run later, after the loop has started.

While this is somewhat similar to asyncio.create_task, it can be used before the loop has started (in which case it will run after the loop has started in the before_server_start listener).

Naming tasks is a good practice as it allows you to cancel them later, and allows Sanic to manage them when the server is stopped, if needed.

[See user guide re: background tasks](/en/guide/basics/tasks#background-tasks)

Args:
task (Union[Future[Any], Coroutine[Any, Any, Any], Awaitable[Any]]):

The future, coroutine, or awaitable to schedule.

name (Optional[str], optional): The name of the task, if needed for

later reference. Defaults to None.

register (bool, optional): Whether to register the task. Defaults

to True.

Returns:

Optional[Task[Any]]: The task that was scheduled, if applicable.

Parameters:
  • task (Union[Future[Any], Coroutine[Any, Any, Any], Awaitable[Any]]) –

  • name (Optional[str]) –

  • register (bool) –

Return type:

Optional[Task[Any]]

add_websocket_route(handler, uri, host=None, strict_slashes=None, subprotocols=None, version=None, name=None, version_prefix='/v', error_format=None, **ctx_kwargs)

A helper method to register a function as a websocket route.

Args:
handler (Callable): A callable function or instance of a class

that can handle the websocket request.

uri (str): URL path that will be mapped to the websocket handler. host (Optional[Union[str, List[str]]]): Host IP or FQDN details. strict_slashes (Optional[bool]): If the API endpoint needs to

terminate with a β€œ/” or not.

subprotocols (Optional[List[str]]): Subprotocols to be used with

websocket handshake.

version (Optional[Union[int, str, float]]): Versioning information. name (Optional[str]): A unique name assigned to the URL. version_prefix (str): URL path before the version value.

Defaults to β€œ/v”.

error_format (Optional[str]): Format for error handling. **ctx_kwargs (Any): Keyword arguments beginning with ctx_*

prefix will be appended to the route context (route.ctx).

Returns:

Callable: Object passed as the handler.

Parameters:
  • uri (str) –

  • host (str | List[str] | None) –

  • strict_slashes (bool | None) –

  • version (int | str | float | None) –

  • name (str | None) –

  • version_prefix (str) –

  • error_format (str | None) –

  • ctx_kwargs (Any) –

after_reload_trigger(listener, *, priority=0)

Decorator for registering a listener for the after_reload_trigger event.

This event is fired only on the reload process and NOT on any worker processes. This event is fired after the reload process triggers the reload. A change event has been detected and the reload process has been triggered.

See [Listeners](/en/guide/basics/listeners) for more details.

Args:

listener (ListenerType[Sanic]): The listener handler to attach.

Examples:

```python @app.after_reload_trigger async def on_after_reload_trigger(app: Sanic, changed: set[str]):

print(β€œAfter reload trigger, changed files: β€œ, changed)

```

Parameters:
  • listener (Callable[[Sanic], Coroutine[Any, Any, None] | None] | Callable[[Sanic, AbstractEventLoop], Coroutine[Any, Any, None] | None] | None) –

  • priority (int) –

Return type:

Callable[[Sanic], Coroutine[Any, Any, None] | None] | Callable[[Sanic, AbstractEventLoop], Coroutine[Any, Any, None] | None]

after_server_start(listener, *, priority=0)

Decorator for registering a listener for the after_server_start event.

This event is fired on all worker processes. You should typically use this event to run background tasks, or perform other actions that are not directly related to handling requests. In theory, it is possible that some requests may be handled before this event is fired, so you should not use this event to initialize resources that are required for handling requests.

A common use case for this event is to start a background task that periodically performs some action, such as clearing a cache or performing a health check.

See [Listeners](/en/guide/basics/listeners) for more details.

Args:

listener (ListenerType[Sanic]): The listener handler to attach.

Examples:

```python @app.after_server_start async def on_after_server_start(app: Sanic):

print(β€œAfter server start”)

```

Parameters:
  • listener (Callable[[Sanic], Coroutine[Any, Any, None] | None] | Callable[[Sanic, AbstractEventLoop], Coroutine[Any, Any, None] | None] | None) –

  • priority (int) –

Return type:

Callable[[Sanic], Coroutine[Any, Any, None] | None] | Callable[[Sanic, AbstractEventLoop], Coroutine[Any, Any, None] | None]

after_server_stop(listener, *, priority=0)

Decorator for registering a listener for the after_server_stop event.

This event is fired on all worker processes. This event is fired after the server has stopped shutting down, and all requests have been handled. You should typically use this event to clean up resources that were initialized in the before_server_start event.

A common use case for this event is to close a database connection pool, or to close a cache client.

See [Listeners](/en/guide/basics/listeners) for more details.

Args:

listener (ListenerType[Sanic]): The listener handler to attach.

Examples:

```python @app.after_server_stop async def on_after_server_stop(app: Sanic):

print(β€œAfter server stop”)

```

Parameters:
  • listener (Callable[[Sanic], Coroutine[Any, Any, None] | None] | Callable[[Sanic, AbstractEventLoop], Coroutine[Any, Any, None] | None] | None) –

  • priority (int) –

Return type:

Callable[[Sanic], Coroutine[Any, Any, None] | None] | Callable[[Sanic, AbstractEventLoop], Coroutine[Any, Any, None] | None]

all_exceptions(handler)

Enables the process of creating a global exception handler as a convenience.

This following two examples are equivalent:

```python @app.exception(Exception) async def handler(request: Request, exception: Exception) -> HTTPResponse:

return text(f”Exception raised: {exception}”)

```

```python @app.all_exceptions async def handler(request: Request, exception: Exception) -> HTTPResponse:

return text(f”Exception raised: {exception}”)

```

Args:

handler (Callable[…, Any]): A coroutine function to handle exceptions.

Returns:
Callable[…, Any]: A decorated method to handle global exceptions for

any route registered under this blueprint.

Parameters:

handler (Callable[[...], Any]) –

Return type:

Callable[[…], Any]

amend()

Context manager to allow changes to the app after it has started.

Typically, once an application has started and is running, you cannot make certain changes, like adding routes, middleware, or signals. This context manager allows you to make those changes, and then finalizes the app again when the context manager exits.

Yields:

None

Example:

```python with app.amend():

app.add_route(handler, β€˜/new_route’)

```

Return type:

Iterator[None]

before_reload_trigger(listener, *, priority=0)

Decorator for registering a listener for the before_reload_trigger event.

This event is fired only on the reload process and NOT on any worker processes. This event is fired before the reload process triggers the reload. A change event has been detected and the reload process is about to be triggered.

See [Listeners](/en/guide/basics/listeners) for more details.

Args:

listener (ListenerType[Sanic]): The listener handler to attach.

Examples:

```python @app.before_reload_trigger async def on_before_reload_trigger(app: Sanic):

print(β€œBefore reload trigger”)

```

Parameters:
  • listener (Callable[[Sanic], Coroutine[Any, Any, None] | None] | Callable[[Sanic, AbstractEventLoop], Coroutine[Any, Any, None] | None] | None) –

  • priority (int) –

Return type:

Callable[[Sanic], Coroutine[Any, Any, None] | None] | Callable[[Sanic, AbstractEventLoop], Coroutine[Any, Any, None] | None]

before_server_start(listener=None, *, priority=0)

Decorator for registering a listener for the before_server_start event.

This event is fired on all worker processes. You should typically use this event to initialize resources that are global in nature, or will be shared across requests and various parts of the application.

A common use case for this event is to initialize a database connection pool, or to initialize a cache client.

See [Listeners](/en/guide/basics/listeners) for more details.

Args:

listener (ListenerType[Sanic]): The listener handler to attach.

Examples:

```python @app.before_server_start async def on_before_server_start(app: Sanic):

print(β€œBefore server start”)

```

Parameters:
  • listener (Callable[[Sanic], Coroutine[Any, Any, None] | None] | Callable[[Sanic, AbstractEventLoop], Coroutine[Any, Any, None] | None] | None) –

  • priority (int) –

Return type:

Callable[[Sanic], Coroutine[Any, Any, None] | None] | Callable[[Sanic, AbstractEventLoop], Coroutine[Any, Any, None] | None]

before_server_stop(listener, *, priority=0)

Decorator for registering a listener for the before_server_stop event.

This event is fired on all worker processes. This event is fired before the server starts shutting down. You should not use this event to perform any actions that are required for handling requests, as some requests may continue to be handled after this event is fired.

A common use case for this event is to stop a background task that was started in the after_server_start event.

See [Listeners](/en/guide/basics/listeners) for more details.

Args:

listener (ListenerType[Sanic]): The listener handler to attach.

Examples:

```python @app.before_server_stop async def on_before_server_stop(app: Sanic):

print(β€œBefore server stop”)

```

Parameters:
  • listener (Callable[[Sanic], Coroutine[Any, Any, None] | None] | Callable[[Sanic, AbstractEventLoop], Coroutine[Any, Any, None] | None] | None) –

  • priority (int) –

Return type:

Callable[[Sanic], Coroutine[Any, Any, None] | None] | Callable[[Sanic, AbstractEventLoop], Coroutine[Any, Any, None] | None]

blueprint(blueprint, *, url_prefix=None, version=None, strict_slashes=None, version_prefix=None, name_prefix=None)

Register a blueprint on the application.

See [Blueprints](/en/guide/best-practices/blueprints) for more information.

Args:

blueprint (Union[Blueprint, Iterable[Blueprint], BlueprintGroup]): Blueprint object or (list, tuple) thereof. url_prefix (Optional[str]): Prefix for all URLs bound to the blueprint. Defaults to None. version (Optional[Union[int, float, str]]): Version prefix for URLs. Defaults to None. strict_slashes (Optional[bool]): Enforce the trailing slashes. Defaults to None. version_prefix (Optional[str]): Prefix for version. Defaults to None. name_prefix (Optional[str]): Prefix for the blueprint name. Defaults to None.

Example:

```python app = Sanic(β€œTestApp”) bp = Blueprint(β€˜TestBP’)

@bp.route(β€˜/route’) def handler(request):

return text(β€˜Hello, Blueprint!’)

app.blueprint(bp, url_prefix=’/blueprint’) ```

Parameters:
  • blueprint (Blueprint | Iterable[Blueprint] | BlueprintGroup) –

  • url_prefix (str | None) –

  • version (int | str | float | None) –

  • strict_slashes (bool | None) –

  • version_prefix (str | None) –

  • name_prefix (str | None) –

Return type:

None

async cancel_task(name, msg=None, *, raise_exception=True)

Cancel a named task.

This method is used to cancel a task by its name. Optionally, you can provide a message that describes why the task was canceled, and control whether an exception should be raised if the task is not found.

Args:

name (str): The name of the task to be canceled. msg (Optional[str]): Optional message describing why the task was canceled. Defaults to None. raise_exception (bool): If True, an exception will be raised if the task is not found. Defaults to True.

Example:

```python async def my_task():

try:

await asyncio.sleep(10)

except asyncio.CancelledError as e:

current_task = asyncio.current_task() print(f”Task {current_task.get_name()} was cancelled. {e}”) # Task sleepy_task was cancelled. No more sleeping!

@app.before_server_start async def before_start(app):

app.add_task(my_task, name=”sleepy_task”) await asyncio.sleep(1) await app.cancel_task(β€œsleepy_task”, msg=”No more sleeping!”)

```

Parameters:
  • name (str) –

  • msg (str | None) –

  • raise_exception (bool) –

Return type:

None

catch_exception(handler)

Register an exception handler for logging or processing.

This method allows the registration of a custom exception handler to catch and process exceptions that occur in the application. Unlike a typical exception handler that might modify the response to the client, this is intended to capture exceptions for logging or other internal processing, such as sending them to an error reporting utility.

Args:
handler (Callable): A coroutine function that takes the application

instance and the exception as arguments. It will be called when an exception occurs within the application’s lifecycle.

Example:

```python app = Sanic(β€œTestApp”)

@app.catch_exception async def report_exception(app: Sanic, exception: Exception):

logging.error(f”An exception occurred: {exception}”)

# Send to an error reporting service await error_service.report(exception)

# Any unhandled exceptions within the application will now be # logged and reported to the error service. ```

Parameters:

handler (Callable[[SignalMixin, Exception], Coroutine[Any, Any, None]]) –

Return type:

None

async create_server(host=None, port=None, *, debug=False, ssl=None, sock=None, protocol=None, backlog=100, access_log=None, unix=None, return_asyncio_server=True, asyncio_server_kwargs=None, noisy_exceptions=None)

Low level API for creating a Sanic Server instance.

This method will create a Sanic Server instance, but will not start it. This is useful for integrating Sanic into other systems. But, you should take caution when using it as it is a low level API and does not perform any of the lifecycle events.

Note

This does not support multiprocessing and is not the preferred way to run a Sanic application. Proceed with caution.

You will need to start the server yourself as shown in the example below. You are responsible for the lifecycle of the server, including app startup using await app.startup(). No events will be triggered for you, so you will need to trigger them yourself if wanted.

Args:

host (Optional[str]): Address to host on. port (Optional[int]): Port to host on. debug (bool): Enables debug output (slows server). ssl (Union[None, SSLContext, dict, str, list, tuple]): SSLContext,

or location of certificate and key for SSL encryption of worker(s).

sock (Optional[socket]): Socket for the server to accept

connections from.

protocol (Optional[Type[Protocol]]): Subclass of

asyncio.Protocol class.

backlog (int): Number of unaccepted connections that the system

will allow before refusing new connections.

access_log (Optional[bool]): Enables writing access logs

(slows server).

return_asyncio_server (bool): _DEPRECATED_ asyncio_server_kwargs (Optional[Dict[str, Any]]): Key-value

arguments for asyncio/uvloop create_server method.

noisy_exceptions (Optional[bool]): Log exceptions that are normally

considered to be quiet/silent.

Returns:
Optional[AsyncioServer]: AsyncioServer if return_asyncio_server

is True else None.

Examples:

```python import asyncio import uvloop from sanic import Sanic, response

app = Sanic(β€œExample”)

@app.route(β€œ/”) async def test(request):

return response.json({β€œanswer”: β€œ42”})

async def main():

server = await app.create_server() await server.startup() await server.serve_forever()

if __name__ == β€œ__main__”:

asyncio.set_event_loop(uvloop.new_event_loop()) asyncio.run(main())

```

Parameters:
  • host (str | None) –

  • port (int | None) –

  • debug (bool) –

  • ssl (None | SSLContext | dict | str | list | tuple) –

  • sock (socket | None) –

  • protocol (Type[Protocol] | None) –

  • backlog (int) –

  • access_log (bool | None) –

  • unix (str | None) –

  • return_asyncio_server (bool) –

  • asyncio_server_kwargs (Dict[str, Any] | None) –

  • noisy_exceptions (bool | None) –

Return type:

AsyncioServer | None

delete(uri, host=None, strict_slashes=None, version=None, name=None, ignore_body=False, version_prefix='/v', error_format=None, **ctx_kwargs)

Decorate a function handler to create a route definition using the DELETE HTTP method.

Args:

uri (str): URL to be tagged to the DELETE method of HTTP. host (Optional[Union[str, List[str]]]): Host IP or FQDN for the

service to use.

strict_slashes (Optional[bool]): Instruct Sanic to check if the

request URLs need to terminate with a /.

version (Optional[Union[int, str, float]]): API Version. name (Optional[str]): Unique name that can be used to identify

the Route.

ignore_body (bool): Whether or not to ignore the body in the

request. Defaults to False.

version_prefix (str): URL path that should be before the version

value. Defaults to β€œ/v”.

error_format (Optional[str]): Custom error format string. **ctx_kwargs (Any): Keyword arguments that begin with a ctx_*

prefix will be appended to the route context (route.ctx).

Returns:

RouteHandler: Object decorated with route method.

Parameters:
  • uri (str) –

  • host (str | List[str] | None) –

  • strict_slashes (bool | None) –

  • version (int | str | float | None) –

  • name (str | None) –

  • ignore_body (bool) –

  • version_prefix (str) –

  • error_format (str | None) –

  • ctx_kwargs (Any) –

Return type:

Callable[[…], Coroutine[Any, Any, HTTPResponse | None]]

dispatch(event: str, *, condition: Dict[str, str] | None = None, context: Dict[str, Any] | None = None, fail_not_found: bool = True, inline: Literal[True], reverse: bool = False) Coroutine[Any, Any, Awaitable[Any]]
dispatch(event: str, *, condition: Dict[str, str] | None = None, context: Dict[str, Any] | None = None, fail_not_found: bool = True, inline: Literal[False] = False, reverse: bool = False) Coroutine[Any, Any, Awaitable[Task]]

Dispatches an event to the signal router.

Args:

event (str): Name of the event to dispatch. condition (Optional[Dict[str, str]]): Condition for the

event dispatch.

context (Optional[Dict[str, Any]]): Context for the event dispatch. fail_not_found (bool): Whether to fail if the event is not found.

Default is True.

inline (bool): If True, returns the result directly. If False,

returns a Task. Default is False.

reverse (bool): Whether to reverse the dispatch order.

Default is False.

Returns:
Coroutine[Any, Any, Awaitable[Union[Task, Any]]]: An awaitable

that returns the result directly if inline=True, or a Task if inline=False.

Examples:

```python @app.signal(β€œuser.registration.created”) async def send_registration_email(**context):

await send_email(context[β€œemail”], template=”registration”)

@app.post(β€œ/register”) async def handle_registration(request):

await do_registration(request) await request.app.dispatch(

β€œuser.registration.created”, context={β€œemail”: request.json.email}

})

```

async static dispatch_delayed_tasks(app, loop)

Signal handler for dispatching delayed tasks.

This is used to dispatch tasks that were added before the loop was started, and will be called after the loop has started. It is not typically used directly.

Args:

app (Sanic): The Sanic application instance. loop (AbstractEventLoop): The event loop in which the tasks are

being run.

Returns:

None

Parameters:
  • app (Sanic) –

  • loop (AbstractEventLoop) –

Return type:

None

enable_websocket(enable=True)

Enable or disable the support for websocket.

Websocket is enabled automatically if websocket routes are added to the application. This typically will not need to be called manually.

Args:
enable (bool, optional): If set to True, enables websocket

support. If set to False, disables websocket support. Defaults to True.

Returns:

None

Parameters:

enable (bool) –

Return type:

None

async event(event, timeout=None, *, condition=None, exclusive=True)

Wait for a specific event to be triggered.

This method waits for a named event to be triggered and can be used in conjunction with the signal system to wait for specific signals. If the event is not found and auto-registration of events is enabled, the event will be registered and then waited on. If the event is not found and auto-registration is not enabled, a NotFound exception is raised.

Auto-registration can be handled by setting the EVENT_AUTOREGISTER config value to True.

`python app.config.EVENT_AUTOREGISTER = True `

Args:

event (str): The name of the event to wait for. timeout (Optional[Union[int, float]]): An optional timeout value

in seconds. If provided, the wait will be terminated if the timeout is reached. Defaults to None, meaning no timeout.

condition: If provided, method will only return when the signal

is dispatched with the given condition.

exclusive: When true (default), the signal can only be dispatched

when the condition has been met. When False, the signal can be dispatched either with or without it.

Raises:
NotFound: If the event is not found and auto-registration of

events is not enabled.

Returns:

The context dict of the dispatched signal.

Examples:

```python async def wait_for_event(app):

while True:

print(”> waiting”) await app.event(β€œfoo.bar.baz”) print(”> event found”)

@app.after_server_start async def after_server_start(app, loop):

app.add_task(wait_for_event(app))

```

Parameters:
  • event (str | Enum) –

  • timeout (int | float | None) –

  • condition (Dict[str, Any] | None) –

  • exclusive (bool) –

Return type:

None

exception(*exceptions, apply=True)

Decorator used to register an exception handler for the current application or blueprint instance.

This method allows you to define a handler for specific exceptions that may be raised within the routes of this blueprint. You can specify one or more exception types to catch, and the handler will be applied to those exceptions.

When used on a Blueprint, the handler will only be applied to routes registered under that blueprint. That means they only apply to requests that have been matched, and the exception is raised within the handler function (or middleware) for that route.

A general exception like NotFound should only be registered on the application instance, not on a blueprint.

See [Exceptions](/en/guide/best-practices/exceptions.html) for more information.

Args:
exceptions (Union[Type[Exception], List[Type[Exception]]]): List of

Python exceptions to be caught by the handler.

apply (bool, optional): Whether the exception handler should be

applied. Defaults to True.

Returns:
Callable: A decorated method to handle global exceptions for any route

registered under this blueprint.

Example:

```python from sanic import Blueprint, text

bp = Blueprint(β€˜my_blueprint’)

@bp.exception(Exception) def handle_exception(request, exception):

return text(β€œOops, something went wrong!”, status=500)

```

```python from sanic import Sanic, NotFound, text

app = Sanic(β€˜MyApp’)

@app.exception(NotFound) def ignore_404s(request, exception):

return text(f”Yep, I totally found the page: {request.url}”)

Parameters:
  • exceptions (Type[Exception] | List[Type[Exception]]) –

  • apply (bool) –

Return type:

Callable

extend(*, extensions=None, built_in_extensions=True, config=None, **kwargs)

Extend Sanic with additional functionality using Sanic Extensions.

This method enables you to add one or more Sanic Extensions to the current Sanic instance. It allows for more control over the Extend object, such as enabling or disabling built-in extensions or providing custom configuration.

See [Sanic Extensions](/en/plugins/sanic-ext/getting-started)

for details.

Args:
extensions (Optional[List[Type[Extension]]], optional): A list of

extensions to add. Defaults to None, meaning only built-in extensions are added.

built_in_extensions (bool, optional): Whether to enable built-in

extensions. Defaults to True.

config (Optional[Union[Config, Dict[str, Any]]], optional):

Optional custom configuration for the extensions. Defaults to None.

**kwargs: Additional keyword arguments that might be needed by

specific extensions.

Returns:

Extend: The Sanic Extensions instance.

Raises:
RuntimeError: If an attempt is made to extend Sanic after Sanic

Extensions has already been set up.

Examples:
A typical use case might be to add a custom extension along with

built-in ones.

```python app.extend(

extensions=[MyCustomExtension], built_in_extensions=True

Parameters:
  • extensions (Optional[List[Type[Extension]]]) –

  • built_in_extensions (bool) –

  • config (Optional[Union[Config, Dict[str, Any]]]) –

Return type:

Extend

finalize()

Finalize the routing configuration for the Sanic application.

This method completes the routing setup by calling the router’s finalize method, and it also finalizes any middleware that has been added to the application. If the application is not in test mode, any finalization errors will be raised.

Finalization consists of identifying defined routes and optimizing Sanic’s performance to meet the application’s specific needs. If you are manually adding routes, after Sanic has started, you will typically want to use the amend context manager rather than calling this method directly.

Note

This method is usually called internally during the server setup process and does not typically need to be invoked manually.

Raises:
FinalizationError: If there is an error during the finalization

process, and the application is not in test mode.

Example:

`python app.finalize() `

Return type:

None

finalize_middleware()

Finalize the middleware configuration for the Sanic application.

This method completes the middleware setup for the application. Middleware in Sanic is used to process requests globally before they reach individual routes or after routes have been processed.

Finalization consists of identifying defined routes and optimizing Sanic’s performance to meet the application’s specific needs. If you are manually adding routes, after Sanic has started, you will typically want to use the amend context manager rather than calling this method directly.

Note

This method is usually called internally during the server setup process and does not typically need to be invoked manually.

Example:

`python app.finalize_middleware() `

Return type:

None

get(uri, host=None, strict_slashes=None, version=None, name=None, ignore_body=True, version_prefix='/v', error_format=None, **ctx_kwargs)

Decorate a function handler to create a route definition using the GET HTTP method.

Args:

uri (str): URL to be tagged to GET method of HTTP. host (Optional[Union[str, List[str]]]): Host IP or FQDN for

the service to use.

strict_slashes (Optional[bool]): Instruct Sanic to check if the

request URLs need to terminate with a /.

version (Optional[Union[int, str, float]]): API Version. name (Optional[str]): Unique name that can be used to identify

the route.

ignore_body (bool): Whether the handler should ignore request

body. This means the body of the request, if sent, will not be consumed. In that instance, you will see a warning in the logs. Defaults to True, meaning do not consume the body.

version_prefix (str): URL path that should be before the version

value. Defaults to β€œ/v”.

error_format (Optional[str]): Custom error format string. **ctx_kwargs (Any): Keyword arguments that begin with a

ctx_* prefix will be appended to the route context (route.ctx).

Returns:

RouteHandler: Object decorated with route method.

Parameters:
  • uri (str) –

  • host (str | List[str] | None) –

  • strict_slashes (bool | None) –

  • version (int | str | float | None) –

  • name (str | None) –

  • ignore_body (bool) –

  • version_prefix (str) –

  • error_format (str | None) –

  • ctx_kwargs (Any) –

Return type:

Callable[[…], Coroutine[Any, Any, HTTPResponse | None]]

static get_address(host, port, version=HTTP.VERSION_1, auto_tls=False)

Retrieve the host address and port, with default values based on the given parameters.

Args:

host (Optional[str]): Host IP or FQDN for the service to use. Defaults to β€œ127.0.0.1”. port (Optional[int]): Port number. Defaults to 8443 if version is 3 or auto_tls=True, else 8000 version (HTTPVersion, optional): HTTP Version. Defaults to HTTP.VERSION_1 (HTTP/1.1). auto_tls (bool, optional): Automatic TLS flag. Defaults to False.

Returns:

Tuple[str, int]: Tuple containing the host and port

Parameters:
  • host (str | None) –

  • port (int | None) –

  • version (HTTP | Literal[1] | ~typing.Literal[3]) –

  • auto_tls (bool) –

Return type:

Tuple[str, int]

classmethod get_app(name=None, *, force_create=False)

Retrieve an instantiated Sanic instance by name.

This method is best used when needing to get access to an already defined application instance in another part of an app.

Warning

Be careful when using this method in the global scope as it is possible that the import path running will cause it to error if the imported global scope runs before the application instance is created.

It is typically best used in a function or method that is called after the application instance has been created.

```python def setup_routes():

app = Sanic.get_app() app.add_route(handler_1, β€˜/route1’) app.add_route(handler_2, β€˜/route2’)

```

Args:
name (Optional[str], optional): Name of the application instance

to retrieve. When not specified, it will return the only application instance if there is only one. If not specified and there are multiple application instances, it will raise an exception. Defaults to None.

force_create (bool, optional): If True and the named app does

not exist, a new instance will be created. Defaults to False.

Returns:

Sanic: The requested Sanic app instance.

Raises:
SanicException: If there are multiple or no Sanic apps found, or

if the specified name is not found.

Example:

`python app1 = Sanic("app1") app2 = Sanic.get_app("app1")  # app2 is the same instance as app1 `

Parameters:
  • name (str | None) –

  • force_create (bool) –

Return type:

Sanic

get_motd_data(server_settings=None)

Retrieves the message of the day (MOTD) data.

Args:
server_settings (Optional[Dict[str, Any]], optional): Settings for

the server. Defaults to None.

Returns:
Tuple[Dict[str, Any], Dict[str, Any]]: A tuple containing two

dictionaries with the relevant MOTD data.

Parameters:

server_settings (Dict[str, Any] | None) –

Return type:

Tuple[Dict[str, Any], Dict[str, Any]]

static get_server_location(server_settings=None)

Using the server settings, retrieve the server location.

Args:
server_settings (Optional[Dict[str, Any]], optional): Settings for

the server. Defaults to None.

Returns:

str: The server location.

Parameters:

server_settings (Dict[str, Any] | None) –

Return type:

str

get_task(name: str, *, raise_exception: Literal[True]) Task
get_task(name: str, *, raise_exception: Literal[False]) Task | None
get_task(name: str, *, raise_exception: bool) Task | None

Get a named task.

This method is used to get a task by its name. Optionally, you can control whether an exception should be raised if the task is not found.

Args:

name (str): The name of the task to be retrieved. raise_exception (bool): If True, an exception will be raised if

the task is not found. Defaults to True.

Returns:

Optional[Task]: The task, if found.

async handle_exception(request, exception, run_middleware=True)

A handler that catches specific exceptions and outputs a response.

Note

This method is typically used internally, and you should not need to call it directly.

Args:

request (Request): The current request object. exception (BaseException): The exception that was raised. run_middleware (bool): Whether to run middleware. Defaults

to True.

Raises:

ServerError: response 500.

Parameters:
  • request (Request) –

  • exception (BaseException) –

  • run_middleware (bool) –

Return type:

None

async handle_request(request)

Handles a request by dispatching it to the appropriate handler.

Note

This method is typically used internally, and you should not need to call it directly.

Args:

request (Request): The current request object.

Raises:

ServerError: response 500.

Parameters:

request (Request) –

Return type:

None

head(uri, host=None, strict_slashes=None, version=None, name=None, ignore_body=True, version_prefix='/v', error_format=None, **ctx_kwargs)

Decorate a function handler to create a route definition using the HEAD HTTP method.

Args:

uri (str): URL to be tagged to HEAD method of HTTP. host (Optional[Union[str, List[str]]]): Host IP or FQDN for

the service to use.

strict_slashes (Optional[bool]): Instruct Sanic to check if the

request URLs need to terminate with a /.

version (Optional[Union[int, str, float]]): API Version. name (Optional[str]): Unique name that can be used to identify

the route.

ignore_body (bool): Whether the handler should ignore request

body. This means the body of the request, if sent, will not be consumed. In that instance, you will see a warning in the logs. Defaults to True, meaning do not consume the body.

version_prefix (str): URL path that should be before the version

value. Defaults to β€œ/v”.

error_format (Optional[str]): Custom error format string. **ctx_kwargs (Any): Keyword arguments that begin with a

ctx_* prefix will be appended to the route context (route.ctx).

Returns:

RouteHandler: Object decorated with route method.

Parameters:
  • uri (str) –

  • host (str | List[str] | None) –

  • strict_slashes (bool | None) –

  • version (int | str | float | None) –

  • name (str | None) –

  • ignore_body (bool) –

  • version_prefix (str) –

  • error_format (str | None) –

  • ctx_kwargs (Any) –

Return type:

Callable[[…], Coroutine[Any, Any, HTTPResponse | None]]

listener(listener_or_event, event_or_none=None, apply=True, *, priority=0)

Create a listener for a specific event in the application’s lifecycle.

See [Listeners](/en/guide/basics/listeners) for more details.

Note

Overloaded signatures allow for different ways of calling this method, depending on the types of the arguments.

Usually, it is prederred to use one of the convenience methods such as before_server_start or after_server_stop instead of calling this method directly.

```python @app.before_server_start async def prefered_method(_):

…

@app.listener(β€œbefore_server_start”) async def not_prefered_method(_):

…

Args:

listener_or_event (Union[ListenerType[Sanic], str]): A listener function or an event name. event_or_none (Optional[str]): The event name to listen for if listener_or_event is a function. Defaults to None. apply (bool): Whether to apply the listener immediately. Defaults to True. priority (int): The priority of the listener. Defaults to 0.

Returns:

Union[ListenerType[Sanic], Callable[[ListenerType[Sanic]], ListenerType[Sanic]]]: The listener or a callable that takes a listener.

Example:

The following code snippet shows how you can use this method as a decorator:

```python @bp.listener(β€œbefore_server_start”) async def before_server_start(app, loop):

…

```

Parameters:
  • listener_or_event (Callable[[Sanic], Coroutine[Any, Any, None] | None] | Callable[[Sanic, AbstractEventLoop], Coroutine[Any, Any, None] | None] | str) –

  • event_or_none (str | None) –

  • apply (bool) –

  • priority (int) –

Return type:

Callable[[Sanic], Coroutine[Any, Any, None] | None] | Callable[[Sanic, AbstractEventLoop], Coroutine[Any, Any, None] | None] | Callable[[Callable[[Sanic], Coroutine[Any, Any, None] | None] | Callable[[Sanic, AbstractEventLoop], Coroutine[Any, Any, None] | None]], Callable[[Sanic], Coroutine[Any, Any, None] | None] | Callable[[Sanic, AbstractEventLoop], Coroutine[Any, Any, None] | None]]

main_process_ready(listener, *, priority=0)

Decorator for registering a listener for the main_process_ready event.

This event is fired only on the main process and NOT on any worker processes. It is fired after the main process has started and the Worker Manager has been initialized (ie, you will have access to app.manager instance). The typical use case for this event is to add a managed process to the Worker Manager.

See [Running custom processes](/en/guide/deployment/manager.html#running-custom-processes) and [Listeners](/en/guide/basics/listeners.html) for more details.

Args:

listener (ListenerType[Sanic]): The listener handler to attach.

Examples:

```python @app.main_process_ready async def on_main_process_ready(app: Sanic):

print(β€œMain process ready”)

```

Parameters:
  • listener (Callable[[Sanic], Coroutine[Any, Any, None] | None] | Callable[[Sanic, AbstractEventLoop], Coroutine[Any, Any, None] | None] | None) –

  • priority (int) –

Return type:

Callable[[Sanic], Coroutine[Any, Any, None] | None] | Callable[[Sanic, AbstractEventLoop], Coroutine[Any, Any, None] | None]

main_process_start(listener, *, priority=0)

Decorator for registering a listener for the main_process_start event.

This event is fired only on the main process and NOT on any worker processes. You should typically use this event to initialize resources that are shared across workers, or to initialize resources that are not safe to be initialized in a worker process.

See [Listeners](/en/guide/basics/listeners) for more details.

Args:

listener (ListenerType[Sanic]): The listener handler to attach.

Examples:

```python @app.main_process_start async def on_main_process_start(app: Sanic):

print(β€œMain process started”)

```

Parameters:
  • listener (Callable[[Sanic], Coroutine[Any, Any, None] | None] | Callable[[Sanic, AbstractEventLoop], Coroutine[Any, Any, None] | None] | None) –

  • priority (int) –

Return type:

Callable[[Sanic], Coroutine[Any, Any, None] | None] | Callable[[Sanic, AbstractEventLoop], Coroutine[Any, Any, None] | None]

main_process_stop(listener, *, priority=0)

Decorator for registering a listener for the main_process_stop event.

This event is fired only on the main process and NOT on any worker processes. You should typically use this event to clean up resources that were initialized in the main_process_start event.

See [Listeners](/en/guide/basics/listeners) for more details.

Args:

listener (ListenerType[Sanic]): The listener handler to attach.

Examples:

```python @app.main_process_stop async def on_main_process_stop(app: Sanic):

print(β€œMain process stopped”)

```

Parameters:
  • listener (Callable[[Sanic], Coroutine[Any, Any, None] | None] | Callable[[Sanic, AbstractEventLoop], Coroutine[Any, Any, None] | None] | None) –

  • priority (int) –

Return type:

Callable[[Sanic], Coroutine[Any, Any, None] | None] | Callable[[Sanic, AbstractEventLoop], Coroutine[Any, Any, None] | None]

make_coffee(*args, **kwargs)

Try for yourself! sanic server:app –coffee

``` β–„β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–„

β–ˆβ–ˆ β–ˆβ–ˆβ–€β–€β–„ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–„β–„β–€

β–€β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–€

```

middleware(middleware_or_request, attach_to='request', apply=True, *, priority=0)

Decorator for registering middleware.

Decorate and register middleware to be called before a request is handled or after a response is created. Can either be called as @app.middleware or @app.middleware(β€˜request’). Although, it is recommended to use @app.on_request or @app.on_response instead for clarity and convenience.

See [Middleware](/guide/basics/middleware) for more information.

Args:
middleware_or_request (Union[Callable, str]): Middleware function

or the keyword β€˜request’ or β€˜response’.

attach_to (str, optional): When to apply the middleware;

either β€˜request’ (before the request is handled) or β€˜response’ (after the response is created). Defaults to β€˜request’.

apply (bool, optional): Whether the middleware should be applied.

Defaults to True.

priority (int, optional): The priority level of the middleware.

Lower numbers are executed first. Defaults to 0.

Returns:
Union[Callable, Callable[[Callable], Callable]]: The decorated

middleware function or a partial function depending on how the method was called.

Example:

```python @app.middleware(β€˜request’) async def custom_middleware(request):

…

```

Parameters:
Return type:

Callable[[Request], HTTPResponse | None | Coroutine[Any, Any, HTTPResponse | None]] | Callable[[Request, BaseHTTPResponse], HTTPResponse | None | Coroutine[Any, Any, HTTPResponse | None]] | Callable[[Callable[[Request], HTTPResponse | None | Coroutine[Any, Any, HTTPResponse | None]] | Callable[[Request, BaseHTTPResponse], HTTPResponse | None | Coroutine[Any, Any, HTTPResponse | None]]], Callable[[Request], HTTPResponse | None | Coroutine[Any, Any, HTTPResponse | None]] | Callable[[Request, BaseHTTPResponse], HTTPResponse | None | Coroutine[Any, Any, HTTPResponse | None]]]

motd(server_settings=None)

Outputs the message of the day (MOTD).

It generally can only be called once per process, and is usually called by the run method in the main process.

Args:
server_settings (Optional[Dict[str, Any]], optional): Settings for

the server. Defaults to None.

Returns:

None

Parameters:

server_settings (Dict[str, Any] | None) –

Return type:

None

on_request(middleware=None, *, priority=0)

Register a middleware to be called before a request is handled.

This is the same as @app.middleware(β€˜request’).

Args:
middleware (Callable, optional): A callable that takes in a

request. Defaults to None.

Returns:
Callable: The decorated middleware function or a partial function

depending on how the method was called.

Examples:

```python @app.on_request async def custom_middleware(request):

request.ctx.custom = β€˜value’

```

Return type:

Callable[[Request], HTTPResponse | None | Coroutine[Any, Any, HTTPResponse | None]] | Callable[[Request, BaseHTTPResponse], HTTPResponse | None | Coroutine[Any, Any, HTTPResponse | None]]

on_response(middleware=None, *, priority=0)

Register a middleware to be called after a response is created.

This is the same as @app.middleware(β€˜response’).

Args:
middleware (Callable, optional): A callable that takes in a

request and response. Defaults to None.

Returns:
Callable: The decorated middleware function or a partial function

depending on how the method was called.

Examples:

```python @app.on_response async def custom_middleware(request, response):

response.headers[β€˜X-Server’] = β€˜Sanic’

```

options(uri, host=None, strict_slashes=None, version=None, name=None, ignore_body=True, version_prefix='/v', error_format=None, **ctx_kwargs)

Decorate a function handler to create a route definition using the OPTIONS HTTP method.

Args:

uri (str): URL to be tagged to OPTIONS method of HTTP. host (Optional[Union[str, List[str]]]): Host IP or FQDN for

the service to use.

strict_slashes (Optional[bool]): Instruct Sanic to check if the

request URLs need to terminate with a /.

version (Optional[Union[int, str, float]]): API Version. name (Optional[str]): Unique name that can be used to identify

the route.

ignore_body (bool): Whether the handler should ignore request

body. This means the body of the request, if sent, will not be consumed. In that instance, you will see a warning in the logs. Defaults to True, meaning do not consume the body.

version_prefix (str): URL path that should be before the version

value. Defaults to β€œ/v”.

error_format (Optional[str]): Custom error format string. **ctx_kwargs (Any): Keyword arguments that begin with a

ctx_* prefix will be appended to the route context (route.ctx).

Returns:

RouteHandler: Object decorated with route method.

Parameters:
  • uri (str) –

  • host (str | List[str] | None) –

  • strict_slashes (bool | None) –

  • version (int | str | float | None) –

  • name (str | None) –

  • ignore_body (bool) –

  • version_prefix (str) –

  • error_format (str | None) –

  • ctx_kwargs (Any) –

Return type:

Callable[[…], Coroutine[Any, Any, HTTPResponse | None]]

patch(uri, host=None, strict_slashes=None, stream=False, version=None, name=None, version_prefix='/v', error_format=None, **ctx_kwargs)

Decorate a function handler to create a route definition using the PATCH HTTP method.

Args:

uri (str): URL to be tagged to PATCH method of HTTP. host (Optional[Union[str, List[str]]]): Host IP or FQDN for

the service to use.

strict_slashes (Optional[bool]): Instruct Sanic to check if the

request URLs need to terminate with a /.

stream (bool): Set to True if full request streaming is needed,

False otherwise. Defaults to False.

version (Optional[Union[int, str, float]]): API Version. name (Optional[str]): Unique name that can be used to identify

the route.

version_prefix (str): URL path that should be before the version

value. Defaults to β€œ/v”.

error_format (Optional[str]): Custom error format string. **ctx_kwargs (Any): Keyword arguments that begin with a

ctx_* prefix will be appended to the route context (route.ctx).

Returns:

RouteHandler: Object decorated with route method.

Parameters:
  • uri (str) –

  • host (str | List[str] | None) –

  • strict_slashes (bool | None) –

  • version (int | str | float | None) –

  • name (str | None) –

  • version_prefix (str) –

  • error_format (str | None) –

  • ctx_kwargs (Any) –

Return type:

Callable[[…], Coroutine[Any, Any, HTTPResponse | None]]

post(uri, host=None, strict_slashes=None, stream=False, version=None, name=None, version_prefix='/v', error_format=None, **ctx_kwargs)

Decorate a function handler to create a route definition using the POST HTTP method.

Args:

uri (str): URL to be tagged to POST method of HTTP. host (Optional[Union[str, List[str]]]): Host IP or FQDN for

the service to use.

strict_slashes (Optional[bool]): Instruct Sanic to check if the

request URLs need to terminate with a /.

stream (bool): Whether or not to stream the request body.

Defaults to False.

version (Optional[Union[int, str, float]]): API Version. name (Optional[str]): Unique name that can be used to identify

the route.

version_prefix (str): URL path that should be before the version

value. Defaults to β€œ/v”.

error_format (Optional[str]): Custom error format string. **ctx_kwargs (Any): Keyword arguments that begin with a

ctx_* prefix will be appended to the route context (route.ctx).

Returns:

RouteHandler: Object decorated with route method.

Parameters:
  • uri (str) –

  • host (str | List[str] | None) –

  • strict_slashes (bool | None) –

  • stream (bool) –

  • version (int | str | float | None) –

  • name (str | None) –

  • version_prefix (str) –

  • error_format (str | None) –

  • ctx_kwargs (Any) –

Return type:

Callable[[…], Coroutine[Any, Any, HTTPResponse | None]]

prepare(host=None, port=None, *, dev=False, debug=False, auto_reload=None, version=HTTP.VERSION_1, ssl=None, sock=None, workers=1, protocol=None, backlog=100, register_sys_signals=True, access_log=None, unix=None, loop=None, reload_dir=None, noisy_exceptions=None, motd=True, fast=False, verbosity=0, motd_display=None, coffee=False, auto_tls=False, single_process=False)

Prepares one or more Sanic applications to be served simultaneously.

This low-level API is typically used when you need to run multiple Sanic applications at the same time. Once prepared, Sanic.serve() should be called in the if __name__ == β€œ__main__” block.

Note

β€œPreparing” and β€œserving” with this function is equivalent to using app.run for a single instance. This should only be used when running multiple applications at the same time.

Args:

host (Optional[str], optional): Hostname to listen on. Defaults to None. port (Optional[int], optional): Port to listen on. Defaults to None. dev (bool, optional): Development mode. Defaults to False. debug (bool, optional): Debug mode. Defaults to False. auto_reload (Optional[bool], optional): Auto reload feature. Defaults to None. version (HTTPVersion, optional): HTTP version to use. Defaults to HTTP.VERSION_1. ssl (Union[None, SSLContext, dict, str, list, tuple], optional): SSL configuration. Defaults to None. sock (Optional[socket], optional): Socket to bind to. Defaults to None. workers (int, optional): Number of worker processes. Defaults to 1. protocol (Optional[Type[Protocol]], optional): Custom protocol class. Defaults to None. backlog (int, optional): Maximum number of pending connections. Defaults to 100. register_sys_signals (bool, optional): Register system signals. Defaults to True. access_log (Optional[bool], optional): Access log. Defaults to None. unix (Optional[str], optional): Unix socket. Defaults to None. loop (Optional[AbstractEventLoop], optional): Event loop. Defaults to None. reload_dir (Optional[Union[List[str], str]], optional): Reload directory. Defaults to None. noisy_exceptions (Optional[bool], optional): Display exceptions. Defaults to None. motd (bool, optional): Display message of the day. Defaults to True. fast (bool, optional): Fast mode. Defaults to False. verbosity (int, optional): Verbosity level. Defaults to 0. motd_display (Optional[Dict[str, str]], optional): Custom MOTD display. Defaults to None. coffee (bool, optional): Coffee mode. Defaults to False. auto_tls (bool, optional): Auto TLS. Defaults to False. single_process (bool, optional): Single process mode. Defaults to False.

Raises:

RuntimeError: Raised when attempting to serve HTTP/3 as a secondary server. RuntimeError: Raised when attempting to use both fast and workers. RuntimeError: Raised when attempting to use single_process with fast, workers, or auto_reload. TypeError: Raised when attempting to use loop with create_server. ValueError: Raised when PROXIES_COUNT is negative.

Examples:

```python if __name__ == β€œ__main__”:

app.prepare() app.serve()

```

Parameters:
  • host (str | None) –

  • port (int | None) –

  • dev (bool) –

  • debug (bool) –

  • auto_reload (bool | None) –

  • version (HTTP | Literal[1] | ~typing.Literal[3]) –

  • ssl (None | SSLContext | dict | str | list | tuple) –

  • sock (socket | None) –

  • workers (int) –

  • protocol (Type[Protocol] | None) –

  • backlog (int) –

  • register_sys_signals (bool) –

  • access_log (bool | None) –

  • unix (str | None) –

  • loop (AbstractEventLoop | None) –

  • reload_dir (str | List[str] | None) –

  • noisy_exceptions (bool | None) –

  • motd (bool) –

  • fast (bool) –

  • verbosity (int) –

  • motd_display (Dict[str, str] | None) –

  • coffee (bool) –

  • auto_tls (bool) –

  • single_process (bool) –

Return type:

None

purge_tasks()

Purges completed and cancelled tasks from the task registry.

This method iterates through the task registry, identifying any tasks that are either done or cancelled, and then removes those tasks, leaving only the pending tasks in the registry.

Return type:

None

put(uri, host=None, strict_slashes=None, stream=False, version=None, name=None, version_prefix='/v', error_format=None, **ctx_kwargs)

Decorate a function handler to create a route definition using the PUT HTTP method.

Args:

uri (str): URL to be tagged to PUT method of HTTP. host (Optional[Union[str, List[str]]]): Host IP or FQDN for

the service to use.

strict_slashes (Optional[bool]): Instruct Sanic to check if the

request URLs need to terminate with a /.

stream (bool): Whether or not to stream the request body.

Defaults to False.

version (Optional[Union[int, str, float]]): API Version. name (Optional[str]): Unique name that can be used to identify

the route.

version_prefix (str): URL path that should be before the version

value. Defaults to β€œ/v”.

error_format (Optional[str]): Custom error format string. **ctx_kwargs (Any): Keyword arguments that begin with a

ctx_* prefix will be appended to the route context (route.ctx).

Returns:

RouteHandler: Object decorated with route method.

Parameters:
  • uri (str) –

  • host (str | List[str] | None) –

  • strict_slashes (bool | None) –

  • stream (bool) –

  • version (int | str | float | None) –

  • name (str | None) –

  • version_prefix (str) –

  • error_format (str | None) –

  • ctx_kwargs (Any) –

Return type:

Callable[[…], Coroutine[Any, Any, HTTPResponse | None]]

refresh(passthru=None)

Refresh the application instance. This is used internally by Sanic.

Warning

This method is intended for internal use only and should not be called directly.

Args:
passthru (Optional[Dict[str, Any]], optional): Optional dictionary

of attributes to pass through to the new instance. Defaults to None.

Returns:

Sanic: The refreshed application instance.

Parameters:

passthru (Dict[str, Any] | None) –

Return type:

Sanic

classmethod register_app(app)

Register a Sanic instance with the class registry.

This method adds a Sanic application instance to the class registry, which is used for tracking all instances of the application. It is usually used internally, but can be used to register an application that may have otherwise been created outside of the class registry.

Args:

app (Sanic): The Sanic instance to be registered.

Raises:
SanicException: If the app is not an instance of Sanic or if the

name of the app is already in use (unless in test mode).

Examples:

`python Sanic.register_app(my_app) `

Parameters:

app (Sanic) –

Return type:

None

register_listener(listener, event, *, priority=0)

Register the listener for a given event.

Args:

listener (Callable): The listener to register. event (str): The event to listen for.

Returns:

Callable: The listener that was registered.

Parameters:
  • listener (Callable[[Sanic], Coroutine[Any, Any, None] | None] | Callable[[Sanic, AbstractEventLoop], Coroutine[Any, Any, None] | None]) –

  • event (str) –

  • priority (int) –

Return type:

Callable[[Sanic], Coroutine[Any, Any, None] | None] | Callable[[Sanic, AbstractEventLoop], Coroutine[Any, Any, None] | None]

register_middleware(middleware, attach_to='request', *, priority=<Default>)

Register a middleware to be called before a request is handled.

Args:

middleware (Callable): A callable that takes in a request. attach_to (str): Whether to attach to request or response.

Defaults to β€˜request’.

priority (int): The priority level of the middleware.

Lower numbers are executed first. Defaults to 0.

Returns:
Union[Callable, Callable[[Callable], Callable]]: The decorated

middleware function or a partial function depending on how the method was called.

Parameters:
Return type:

Callable[[Request], HTTPResponse | None | Coroutine[Any, Any, HTTPResponse | None]] | Callable[[Request, BaseHTTPResponse], HTTPResponse | None | Coroutine[Any, Any, HTTPResponse | None]] | Middleware

register_named_middleware(middleware, route_names, attach_to='request', *, priority=<Default>)

Used to register named middleqare (middleware typically on blueprints)

Args:

middleware (Callable): A callable that takes in a request. route_names (Iterable[str]): The route names to attach the

middleware to.

attach_to (str): Whether to attach to request or response.

Defaults to β€˜request’.

priority (int): The priority level of the middleware.

Lower numbers are executed first. Defaults to 0.

Returns:
Union[Callable, Callable[[Callable], Callable]]: The decorated

middleware function or a partial function depending on how the method was called.

Parameters:
reload_process_start(listener, *, priority=0)

Decorator for registering a listener for the reload_process_start event.

This event is fired only on the reload process and NOT on any worker processes. This is similar to the main_process_start event, except that it is fired only when the reload process is started.

See [Listeners](/en/guide/basics/listeners) for more details.

Args:

listener (ListenerType[Sanic]): The listener handler to attach.

Examples:

```python @app.reload_process_start async def on_reload_process_start(app: Sanic):

print(β€œReload process started”)

```

Parameters:
  • listener (Callable[[Sanic], Coroutine[Any, Any, None] | None] | Callable[[Sanic, AbstractEventLoop], Coroutine[Any, Any, None] | None] | None) –

  • priority (int) –

Return type:

Callable[[Sanic], Coroutine[Any, Any, None] | None] | Callable[[Sanic, AbstractEventLoop], Coroutine[Any, Any, None] | None]

reload_process_stop(listener, *, priority=0)

Decorator for registering a listener for the reload_process_stop event.

This event is fired only on the reload process and NOT on any worker processes. This is similar to the main_process_stop event, except that it is fired only when the reload process is stopped.

See [Listeners](/en/guide/basics/listeners) for more details.

Args:

listener (ListenerType[Sanic]): The listener handler to attach.

Examples:

```python @app.reload_process_stop async def on_reload_process_stop(app: Sanic):

print(β€œReload process stopped”)

```

Parameters:
  • listener (Callable[[Sanic], Coroutine[Any, Any, None] | None] | Callable[[Sanic, AbstractEventLoop], Coroutine[Any, Any, None] | None] | None) –

  • priority (int) –

Return type:

Callable[[Sanic], Coroutine[Any, Any, None] | None] | Callable[[Sanic, AbstractEventLoop], Coroutine[Any, Any, None] | None]

report_exception(handler)

Register a handler to report exceptions.

A convenience method to register a handler for the signal that is emitted when an exception occurs. It is typically used to report exceptions to an external service.

It is equivalent to:

```python @app.signal(Event.SERVER_EXCEPTION_REPORT) async def report(exception):

await do_something_with_error(exception)

```

Args:
handler (Callable[[Sanic, Exception], Coroutine[Any, Any, None]]):

The handler to register.

Returns:
Callable[[Sanic, Exception], Coroutine[Any, Any, None]]: The

handler that was registered.

Parameters:

handler (Callable[[Sanic, Exception], Coroutine[Any, Any, None]]) –

Return type:

Callable[[Exception], Coroutine[Any, Any, None]]

route(uri, methods=None, host=None, strict_slashes=None, stream=False, version=None, name=None, ignore_body=False, apply=True, subprotocols=None, websocket=False, unquote=False, static=False, version_prefix='/v', error_format=None, **ctx_kwargs)

Decorate a function to be registered as a route.

Args:

uri (str): Path of the URL. methods (Optional[Iterable[str]]): List or tuple of

methods allowed.

host (Optional[Union[str, List[str]]]): The host, if required. strict_slashes (Optional[bool]): Whether to apply strict slashes

to the route.

stream (bool): Whether to allow the request to stream its body. version (Optional[Union[int, str, float]]): Route specific

versioning.

name (Optional[str]): User-defined route name for url_for. ignore_body (bool): Whether the handler should ignore request

body (e.g. GET requests).

apply (bool): Apply middleware to the route. subprotocols (Optional[List[str]]): List of subprotocols. websocket (bool): Enable WebSocket support. unquote (bool): Unquote special characters in the URL path. static (bool): Enable static route. version_prefix (str): URL path that should be before the version

value; default: β€œ/v”.

error_format (Optional[str]): Error format for the route. ctx_kwargs (Any): Keyword arguments that begin with a ctx_*

prefix will be appended to the route context (route.ctx).

Returns:

RouteWrapper: Tuple of routes, decorated function.

Examples:

Using the method to define a GET endpoint:

```python @app.route(β€œ/hello”) async def hello(request: Request):

return text(β€œHello, World!”)

```

Adding context kwargs to the route:

```python @app.route(β€œ/greet”, ctx_name=”World”) async def greet(request: Request):

name = request.route.ctx.name return text(f”Hello, {name}!”)

```

Parameters:
  • uri (str) –

  • methods (Iterable[str] | None) –

  • host (str | List[str] | None) –

  • strict_slashes (bool | None) –

  • stream (bool) –

  • version (int | str | float | None) –

  • name (str | None) –

  • ignore_body (bool) –

  • apply (bool) –

  • subprotocols (List[str] | None) –

  • websocket (bool) –

  • unquote (bool) –

  • static (bool) –

  • version_prefix (str) –

  • error_format (str | None) –

  • ctx_kwargs (Any) –

Return type:

Callable[[Callable[[…], Coroutine[Any, Any, HTTPResponse | None]]], Callable[[…], Coroutine[Any, Any, HTTPResponse | None]] | Tuple[Route, Callable[[…], Coroutine[Any, Any, HTTPResponse | None]]]]

run(host=None, port=None, *, dev=False, debug=False, auto_reload=None, version=HTTP.VERSION_1, ssl=None, sock=None, workers=1, protocol=None, backlog=100, register_sys_signals=True, access_log=None, unix=None, loop=None, reload_dir=None, noisy_exceptions=None, motd=True, fast=False, verbosity=0, motd_display=None, auto_tls=False, single_process=False)

Run the HTTP Server and listen until keyboard interrupt or term signal. On termination, drain connections before closing.

Note

When you need control over running the Sanic instance, this is the method to use. However, in most cases the preferred method is to use the CLI command:

`sh sanic server:app` `

If you are using this method to run Sanic, make sure you do the following:

  1. Use if __name__ == β€œ__main__” to guard the code.

  2. Do NOT define the app instance inside the if block.

See [Dynamic Applications](/en/guide/deployment/app-loader) for more information about the second point.

Args:

host (Optional[str]): Address to host on. port (Optional[int]): Port to host on. dev (bool): Run the server in development mode. debug (bool): Enables debug output (slows server). auto_reload (Optional[bool]): Reload app whenever its source code is changed.

Enabled by default in debug mode.

version (HTTPVersion): HTTP Version. ssl (Union[None, SSLContext, dict, str, list, tuple]): SSLContext, or location of certificate and key

for SSL encryption of worker(s).

sock (Optional[socket]): Socket for the server to accept connections from. workers (int): Number of processes received before it is respected. protocol (Optional[Type[Protocol]]): Subclass of asyncio Protocol class. backlog (int): A number of unaccepted connections that the system will allow

before refusing new connections.

register_sys_signals (bool): Register SIG* events. access_log (Optional[bool]): Enables writing access logs (slows server). unix (Optional[str]): Unix socket to listen on instead of TCP port. loop (Optional[AbstractEventLoop]): AsyncIO event loop. reload_dir (Optional[Union[List[str], str]]): Directory to watch for code changes, if auto_reload is True. noisy_exceptions (Optional[bool]): Log exceptions that are normally considered to be quiet/silent. motd (bool): Display Message of the Day. fast (bool): Enable fast mode. verbosity (int): Verbosity level. motd_display (Optional[Dict[str, str]]): Customize Message of the Day display. auto_tls (bool): Enable automatic TLS certificate handling. single_process (bool): Enable single process mode.

Returns:

None

Raises:

RuntimeError: Raised when attempting to serve HTTP/3 as a secondary server. RuntimeError: Raised when attempting to use both fast and workers. RuntimeError: Raised when attempting to use single_process with fast, workers, or auto_reload. TypeError: Raised when attempting to use loop with create_server. ValueError: Raised when PROXIES_COUNT is negative.

Examples:

```python from sanic import Sanic, Request, json

app = Sanic(β€œTestApp”)

@app.get(β€œ/”) async def handler(request: Request):

return json({β€œfoo”: β€œbar”})

if __name__ == β€œ__main__”:

app.run(port=9999, dev=True)

```

Parameters:
  • host (str | None) –

  • port (int | None) –

  • dev (bool) –

  • debug (bool) –

  • auto_reload (bool | None) –

  • version (HTTP | Literal[1] | ~typing.Literal[3]) –

  • ssl (None | SSLContext | dict | str | list | tuple) –

  • sock (socket | None) –

  • workers (int) –

  • protocol (Type[Protocol] | None) –

  • backlog (int) –

  • register_sys_signals (bool) –

  • access_log (bool | None) –

  • unix (str | None) –

  • loop (AbstractEventLoop | None) –

  • reload_dir (str | List[str] | None) –

  • noisy_exceptions (bool | None) –

  • motd (bool) –

  • fast (bool) –

  • verbosity (int) –

  • motd_display (Dict[str, str] | None) –

  • auto_tls (bool) –

  • single_process (bool) –

Return type:

None

async static run_delayed_task(app, loop, task)

Executes a delayed task within the context of a given app and loop.

This method prepares a given task by invoking the app’s private _prep_task method and then awaits the execution of the prepared task.

Args:
app (Any): The application instance on which the task will

be executed.

loop (AbstractEventLoop): The event loop where the task will

be scheduled.

task (Task[Any]): The task function that will be prepared

and executed.

Returns:

None

Parameters:
  • app (Sanic) –

  • loop (AbstractEventLoop) –

  • task (Task[Any]) –

Return type:

None

classmethod serve(primary=None, *, app_loader=None, factory=None)

Serve one or more Sanic applications.

This is the main entry point for running Sanic applications. It should be called in the if __name__ == β€œ__main__” block.

Args:
primary (Optional[Sanic], optional): The primary Sanic application

to serve. Defaults to None.

app_loader (Optional[AppLoader], optional): An AppLoader instance

to use for loading applications. Defaults to None.

factory (Optional[Callable[[], Sanic]], optional): A factory

function to use for loading applications. Defaults to None.

Raises:

RuntimeError: Raised when no applications are found. RuntimeError: Raised when no server information is found for the

primary application.

RuntimeError: Raised when attempting to use loop with

create_server.

RuntimeError: Raised when attempting to use single_process with

fast, workers, or auto_reload.

RuntimeError: Raised when attempting to serve HTTP/3 as a

secondary server.

RuntimeError: Raised when attempting to use both fast and

workers.

TypeError: Raised when attempting to use loop with

create_server.

ValueError: Raised when PROXIES_COUNT is negative.

Examples:

```python if __name__ == β€œ__main__”:

app.prepare() Sanic.serve()

```

Parameters:
  • primary (Optional[Sanic]) –

  • app_loader (Optional[AppLoader]) –

  • factory (Optional[Callable[[], Sanic]]) –

Return type:

None

classmethod serve_single(primary=None)

Serve a single process of a Sanic application.

Similar to serve, but only serves a single process. When used, certain features are disabled, such as fast, workers, multiplexer, auto_reload, and the Inspector. It is almost never needed to use this method directly. Instead, you should use the CLI:

`sh sanic app.sanic:app --single-process `

Or, if you need to do it programmatically, you should use the single_process argument of run:

`python app.run(single_process=True) `

Args:
primary (Optional[Sanic], optional): The primary Sanic application

to serve. Defaults to None.

Raises:

RuntimeError: Raised when no applications are found. RuntimeError: Raised when no server information is found for the

primary application.

RuntimeError: Raised when attempting to serve HTTP/3 as a

secondary server.

RuntimeError: Raised when attempting to use both fast and

workers.

ValueError: Raised when PROXIES_COUNT is negative.

Parameters:

primary (Optional[Sanic]) –

Return type:

None

set_serving(serving)

Set the serving state of the application.

This method is used to set the serving state of the application. It is used internally by Sanic and should not typically be called manually.

Args:

serving (bool): Whether the application is serving.

Parameters:

serving (bool) –

Return type:

None

setup_loop()

Set up the event loop.

An internal method that sets up the event loop to uvloop if possible, or a Windows selector loop if on Windows.

Returns:

None

Return type:

None

classmethod should_auto_reload()

Check if any applications have auto-reload enabled.

Returns:
bool: True if any applications have auto-reload enabled, else

False.

Return type:

bool

shutdown_tasks(timeout=None, increment=0.1)

Cancel all tasks except the server task.

This method is used to cancel all tasks except the server task. It iterates through the task registry, cancelling all tasks except the server task, and then waits for the tasks to complete. Optionally, you can provide a timeout and an increment to control how long the method will wait for the tasks to complete.

Args:
timeout (Optional[float]): The amount of time to wait for the tasks

to complete. Defaults to None.

increment (float): The amount of time to wait between checks for

whether the tasks have completed. Defaults to 0.1.

Parameters:
  • timeout (float | None) –

  • increment (float) –

Return type:

None

signal(event, *, apply=True, condition=None, exclusive=True, priority=0)

For creating a signal handler, used similar to a route handler:

@app.signal("foo.bar.<thing>")
async def signal_handler(thing, **kwargs):
    print(f"[signal_handler] {thing=}", kwargs)
Parameters:
  • event (str) – Representation of the event in one.two.three form

  • apply (bool, optional) – For lazy evaluation, defaults to True

  • condition (Dict[str, Any], optional) – For use with the condition argument in dispatch filtering, defaults to None

  • exclusive (bool) – When True, the signal can only be dispatched when the condition has been met. When False, the signal can be dispatched either with or without it. THIS IS INAPPLICABLE TO BLUEPRINT SIGNALS. THEY ARE ALWAYS NON-EXCLUSIVE, defaults to True

  • priority (int) –

Return type:

Callable[[Callable[[…], Coroutine[Any, Any, None]]], Callable[[…], Coroutine[Any, Any, None]]]

signalize(allow_fail_builtin=True)

Finalize the signal handling configuration for the Sanic application.

This method completes the signal handling setup by calling the signal router’s finalize method. If the application is not in test mode, any finalization errors will be raised.

Finalization consists of identifying defined signaliz and optimizing Sanic’s performance to meet the application’s specific needs. If you are manually adding signals, after Sanic has started, you will typically want to use the amend context manager rather than calling this method directly.

Note

This method is usually called internally during the server setup process and does not typically need to be invoked manually.

Args:
allow_fail_builtin (bool, optional): If set to True, will allow

built-in signals to fail during the finalization process. Defaults to True.

Raises:
FinalizationError: If there is an error during the signal

finalization process, and the application is not in test mode.

Example:

`python app.signalize(allow_fail_builtin=False) `

Parameters:

allow_fail_builtin (bool) –

Return type:

None

static(uri, file_or_directory, pattern='/?.+', use_modified_since=True, use_content_range=False, stream_large_files=False, name='static', host=None, strict_slashes=None, content_type=None, apply=True, resource_type=None, index=None, directory_view=False, directory_handler=None)

Register a root to serve files from. The input can either be a file or a directory.

This method provides an easy and simple way to set up the route necessary to serve static files.

Args:

uri (str): URL path to be used for serving static content. file_or_directory (Union[PathLike, str]): Path to the static file

or directory with static files.

pattern (str, optional): Regex pattern identifying the valid

static files. Defaults to r”/?.+”.

use_modified_since (bool, optional): If true, send file modified

time, and return not modified if the browser’s matches the server’s. Defaults to True.

use_content_range (bool, optional): If true, process header for

range requests and sends the file part that is requested. Defaults to False.

stream_large_files (Union[bool, int], optional): If True, use

the StreamingHTTPResponse.file_stream handler rather than the HTTPResponse.file handler to send the file. If this is an integer, it represents the threshold size to switch to StreamingHTTPResponse.file_stream. Defaults to False, which means that the response will not be streamed.

name (str, optional): User-defined name used for url_for.

Defaults to β€œstatic”.

host (Optional[str], optional): Host IP or FQDN for the

service to use.

strict_slashes (Optional[bool], optional): Instruct Sanic to

check if the request URLs need to terminate with a slash.

content_type (Optional[str], optional): User-defined content type

for header.

apply (bool, optional): If true, will register the route

immediately. Defaults to True.

resource_type (Optional[str], optional): Explicitly declare a

resource to be a β€œfile” or a β€œdir”.

index (Optional[Union[str, Sequence[str]]], optional): When

exposing against a directory, index is the name that will be served as the default file. When multiple file names are passed, then they will be tried in order.

directory_view (bool, optional): Whether to fallback to showing

the directory viewer when exposing a directory. Defaults to False.

directory_handler (Optional[DirectoryHandler], optional): An

instance of DirectoryHandler that can be used for explicitly controlling and subclassing the behavior of the default directory handler.

Returns:

List[sanic.router.Route]: Routes registered on the router.

Examples:

Serving a single file: `python app.static('/foo', 'path/to/static/file.txt') `

Serving all files from a directory: `python app.static('/static', 'path/to/static/directory') `

Serving large files with a specific threshold: `python app.static('/static', 'path/to/large/files', stream_large_files=1000000) `

Parameters:
  • uri (str) –

  • file_or_directory (PathLike | str) –

  • pattern (str) –

  • use_modified_since (bool) –

  • use_content_range (bool) –

  • stream_large_files (bool | int) –

  • name (str) –

  • host (str | None) –

  • strict_slashes (bool | None) –

  • content_type (str | None) –

  • apply (bool) –

  • resource_type (str | None) –

  • index (str | Sequence[str] | None) –

  • directory_view (bool) –

  • directory_handler (DirectoryHandler | None) –

stop(terminate=True, unregister=False)

This kills the Sanic server, cleaning up after itself.

Args:
terminate (bool): Force kill all requests immediately without

allowing them to finish processing.

unregister (bool): Unregister the app from the global registry.

Returns:

None

Parameters:
  • terminate (bool) –

  • unregister (bool) –

Return type:

None

classmethod unregister_app(app)

Unregister a Sanic instance from the class registry.

This method removes a previously registered Sanic application instance from the class registry. This can be useful for cleanup purposes, especially in testing or when an app instance is no longer needed. But, it is typically used internally and should not be needed in most cases.

Args:

app (Sanic): The Sanic instance to be unregistered.

Raises:

SanicException: If the app is not an instance of Sanic.

Examples:

`python Sanic.unregister_app(my_app) `

Parameters:

app (Sanic) –

Return type:

None

update_config(config)

Update the application configuration.

This method is used to update the application configuration. It can accept a configuration object, a dictionary, or a path to a file that contains a configuration object or dictionary.

See [Configuration](/en/guide/deployment/configuration) for details.

Args:
config (Union[bytes, str, dict, Any]): The configuration object,

dictionary, or path to a configuration file.

Parameters:

config (bytes | str | dict | Any) –

Return type:

None

url_for(view_name, **kwargs)

Build a URL based on a view name and the values provided.

This method constructs URLs for a given view name, taking into account various special keyword arguments that can be used to modify the resulting URL. It can handle internal routing as well as external URLs with different schemes.

There are several special keyword arguments that can be used to modify the URL that is built. They each begin with an underscore. They are:

  • _anchor

  • _external

  • _host

  • _server

  • _scheme

Args:

view_name (str): String referencing the view name. _anchor (str): Adds an β€œ#anchor” to the end. _scheme (str): Should be either β€œhttp” or β€œhttps”, default is β€œhttp”. _external (bool): Whether to return the path or a full URL with scheme and host. _host (str): Used when one or more hosts are defined for a route to tell Sanic which to use. _server (str): If not using β€œ_host”, this will be used for defining the hostname of the URL. **kwargs: Keys and values that are used to build request parameters and

query string arguments.

Raises:

URLBuildError: If there are issues with constructing the URL.

Returns:

str: The built URL.

Examples:

Building a URL for a specific view with parameters: `python url_for('view_name', param1='value1', param2='value2') # /view-name?param1=value1&param2=value2 `

Creating an external URL with a specific scheme and anchor: `python url_for('view_name', _scheme='https', _external=True, _anchor='section1') # https://example.com/view-name#section1 `

Creating a URL with a specific host: ```python url_for(β€˜view_name’, _host=’subdomain.example.com’) # http://subdomain.example.com/view-name

Parameters:

view_name (str) –

websocket(uri, host=None, strict_slashes=None, subprotocols=None, version=None, name=None, apply=True, version_prefix='/v', error_format=None, **ctx_kwargs)

Decorate a function to be registered as a websocket route.

Args:

uri (str): Path of the URL. host (Optional[Union[str, List[str]]]): Host IP or FQDN details. strict_slashes (Optional[bool]): If the API endpoint needs to

terminate with a β€œ/” or not.

subprotocols (Optional[List[str]]): Optional list of str with

supported subprotocols.

version (Optional[Union[int, str, float]]): WebSocket

protocol version.

name (Optional[str]): A unique name assigned to the URL so that

it can be used with url_for.

apply (bool): If set to False, it doesn’t apply the route to the

app. Default is True.

version_prefix (str): URL path that should be before the version

value. Defaults to β€œ/v”.

error_format (Optional[str]): Custom error format string. **ctx_kwargs (Any): Keyword arguments that begin with

a ctx_* prefix will be appended to the route context (route.ctx).

Returns:

tuple: Tuple of routes, decorated function.

Parameters:
  • uri (str) –

  • host (str | List[str] | None) –

  • strict_slashes (bool | None) –

  • subprotocols (List[str] | None) –

  • version (int | str | float | None) –

  • name (str | None) –

  • apply (bool) –

  • version_prefix (str) –

  • error_format (str | None) –

  • ctx_kwargs (Any) –

property asgi: bool

Whether the app is running in ASGI mode.

property asgi_client: SanicASGITestClient

A testing client that uses ASGI to reach into the application to execute handlers.

This property is available if the sanic-testing package is installed.

See [Test Clients](/en/plugins/sanic-testing/clients#asgi-async-client-sanicasgitestclient) for details.

Returns:

SanicASGITestClient: A testing client from the sanic-testing package.

property auto_reload: bool

Whether the app is running in auto-reload mode.

property debug: bool

Whether the app is running in debug mode.

property ext: Extend

Convenience property for accessing Sanic Extensions.

This property is available if the sanic-ext package is installed.

See [Sanic Extensions](/en/plugins/sanic-ext/getting-started)

for details.

Returns:

Extend: The Sanic Extensions instance.

Examples:

A typical use case might be for registering a dependency injection. `python app.ext.dependency(SomeObject()) `

property inspector: Inspector

An instance of Inspector for accessing the application’s state.

This can only be accessed from a worker process, and only if the inspector has been enabled.

See [Inspector](/en/guide/deployment/inspector) for details.

Returns:

Inspector: An instance of Inspector.

property loop: AbstractEventLoop

Synonymous with asyncio.get_event_loop().

Note

Only supported when using the app.run method.

Returns:

AbstractEventLoop: The event loop for the application.

Raises:

SanicException: If the application is not running.

property m: WorkerMultiplexer

Interface for interacting with the worker processes

This is a shortcut for app.multiplexer. It is available only in a worker process using the Sanic server. It allows you to interact with the worker processes, such as sending messages and commands.

See [Access to the multiplexer](/en/guide/deployment/manager#access-to-the-multiplexer) for more information.

Returns:

WorkerMultiplexer: The worker multiplexer instance

Examples:

```python app.m.restart() # restarts the worker app.m.terminate() # terminates the worker app.m.scale(4) # scales the number of workers to 4

```

property manager: WorkerManager

Property to access the WorkerManager instance.

This property provides access to the WorkerManager object controlling the worker processes. It can only be accessed from the main process.

Note

Make sure to only access this property from the main process, as attempting to do so from a worker process will result in an exception.

See [WorkerManager](/en/guide/deployment/manager) for details.

Returns:
WorkerManager: The manager responsible for managing

worker processes.

Raises:
SanicException: If an attempt is made to access the manager

from a worker process or if the manager is not initialized.

Example:

`python app.manager.manage(...) `

property reload_dirs: Set[Path]

The directories that are monitored for auto-reload.

Returns:
Set[str]: The set of directories that are monitored for

auto-reload.

property serve_location: str

Retrieve the server location.

Returns:

str: The server location.

property state: ApplicationState

The application state.

Returns:

ApplicationState: The current state of the application.

property tasks: Iterable[Task[Any]]

The tasks that are currently registered with the application.

Returns:
Iterable[Task[Any]]: The tasks that are currently registered with

the application.

property test_client: SanicTestClient

A testing client that uses httpx and a live running server to reach into the application to execute handlers.

This property is available if the sanic-testing package is installed.

See [Test Clients](/en/plugins/sanic-testing/clients#wsgi-client-sanictestclient) for details.

Returns:

SanicTestClient: A testing client from the sanic-testing package.

sanic.config

class sanic.config.Config(defaults=None, env_prefix='SANIC_', keep_alive=None, *, converters=None)

Bases: dict

Configuration object for Sanic.

You can use this object to both: (1) configure how Sanic will operate, and (2) manage your application’s custom configuration values.

Parameters:
  • defaults (Optional[Dict[str, Union[str, bool, int, float, None]]]) –

  • env_prefix (Optional[str]) –

  • keep_alive (Optional[bool]) –

  • converters (Optional[Sequence[Callable[[str], Any]]]) –

load(config)

Update app.config.

Note

Only upper case settings are considered

See [Configuration](/en/guide/deployment/configuration) for more details.

Args:
config (Union[bytes, str, dict, Any]): Path to py file holding

settings, dict holding settings, or any object holding settings.

Examples:

You can upload app config by providing path to py file holding settings.

`python # /some/py/file A = 1 B = 2 `

`python config.update_config("${some}/py/file") `

Yes you can put environment variable here, but they must be provided in format: ${some_env_var}, and mark that $some_env_var is treated as plain string.

You can upload app config by providing dict holding settings.

`python d = {"A": 1, "B": 2} config.update_config(d) `

You can upload app config by providing any object holding settings, but in such case config.__dict__ will be used as dict holding settings.

```python class C:

A = 1 B = 2

config.update_config(C) ```

Parameters:

config (bytes | str | dict | Any) –

load_environment_vars(prefix='SANIC_')

Load environment variables into the config.

Looks for prefixed environment variables and applies them to the configuration if present. This is called automatically when Sanic starts up to load environment variables into config. Environment variables should start with the defined prefix and should only contain uppercase letters.

It will automatically hydrate the following types:

  • int

  • float

  • bool

Anything else will be imported as a str. If you would like to add additional types to this list, you can use sanic.config.Config.register_type(). Just make sure that they are registered before you instantiate your application.

You likely won’t need to call this method directly.

See [Configuration](/en/guide/deployment/configuration) for more details.

Args:
prefix (str): The prefix to use when looking for environment

variables. Defaults to SANIC_.

Examples:

```python # Environment variables # SANIC_SERVER_NAME=example.com # SANIC_SERVER_PORT=9999 # SANIC_SERVER_AUTORELOAD=true

# Python app.config.load_environment_vars() ```

register_type(converter)

Register a custom type converter.

Allows for adding custom function to cast from a string value to any other type. The function should raise ValueError if it is not the correct type.

Args:
converter (Callable[[str], Any]): A function that takes a string

and returns a value of any type.

Examples:

```python def my_converter(value: str) -> Any:

# Do something to convert the value return value

config.register_type(my_converter) ```

Parameters:

converter (Callable[[str], Any]) –

Return type:

None

update(*other, **kwargs)

Update the config with new values.

This method will update the config with the values from the provided other objects, and then update the config with the provided kwargs. The other objects can be any object that can be converted to a dictionary, such as a dict, Config object, or str path to a Python file. The kwargs must be a dictionary of key-value pairs.

Note

Only upper case settings are considered

Args:
*other: Any number of objects that can be converted to a

dictionary.

**kwargs: Any number of key-value pairs.

Raises:

AttributeError: If a key is not in the config.

Examples:

```python config.update(

{β€œA”: 1, β€œB”: 2}, {β€œC”: 3, β€œD”: 4}, E=5, F=6,

Parameters:
  • other (Any) –

  • kwargs (Any) –

Return type:

None

update_config(config)

Update app.config.

Note

Only upper case settings are considered

See [Configuration](/en/guide/deployment/configuration) for more details.

Args:
config (Union[bytes, str, dict, Any]): Path to py file holding

settings, dict holding settings, or any object holding settings.

Examples:

You can upload app config by providing path to py file holding settings.

`python # /some/py/file A = 1 B = 2 `

`python config.update_config("${some}/py/file") `

Yes you can put environment variable here, but they must be provided in format: ${some_env_var}, and mark that $some_env_var is treated as plain string.

You can upload app config by providing dict holding settings.

`python d = {"A": 1, "B": 2} config.update_config(d) `

You can upload app config by providing any object holding settings, but in such case config.__dict__ will be used as dict holding settings.

```python class C:

A = 1 B = 2

config.update_config(C) ```

Parameters:

config (bytes | str | dict | Any) –

class sanic.config.DescriptorMeta(name, bases, namespace, **kwargs)

Bases: ABCMeta

Metaclass for Config.

sanic.application.constants

enum sanic.application.constants.Mode(value)

Bases: StrEnum

Server modes.

Member Type:

str

Valid values are as follows:

PRODUCTION = <Mode.PRODUCTION: 'production'>
DEBUG = <Mode.DEBUG: 'debug'>
enum sanic.application.constants.Server(value)

Bases: StrEnum

Server types.

Member Type:

str

Valid values are as follows:

SANIC = <Server.SANIC: 'sanic'>
ASGI = <Server.ASGI: 'asgi'>
enum sanic.application.constants.ServerStage(value)

Bases: IntEnum

Server stages.

Member Type:

int

Valid values are as follows:

STOPPED = <ServerStage.STOPPED: 1>
PARTIAL = <ServerStage.PARTIAL: 2>
SERVING = <ServerStage.SERVING: 3>

sanic.application.state

class sanic.application.state.ApplicationServerInfo(settings, stage=ServerStage.STOPPED, server=None)

Bases: object

Information about a server instance.

Parameters:
class sanic.application.state.ApplicationState(app, asgi=False, coffee=False, fast=False, host='', port=0, ssl=None, sock=None, unix=None, mode=Mode.PRODUCTION, reload_dirs=<factory>, auto_reload=False, server=Server.SANIC, is_running=False, is_started=False, is_stopping=False, verbosity=0, workers=0, primary=True, server_info=<factory>, _init=False)

Bases: object

Application state.

This class is used to store the state of the application. It is instantiated by the application and is available as app.state.

Parameters:
  • app (Sanic) –

  • asgi (bool) –

  • coffee (bool) –

  • fast (bool) –

  • host (str) –

  • port (int) –

  • ssl (Optional[SSLContext]) –

  • sock (Optional[socket]) –

  • unix (Optional[str]) –

  • mode (Mode) –

  • reload_dirs (Set[Path]) –

  • auto_reload (bool) –

  • server (Server) –

  • is_running (bool) –

  • is_started (bool) –

  • is_stopping (bool) –

  • verbosity (int) –

  • workers (int) –

  • primary (bool) –

  • server_info (List[ApplicationServerInfo]) –

  • _init (bool) –

set_verbosity(value)

Set the verbosity level.

Args:

value (int): Verbosity level.

Parameters:

value (int) –

Return type:

None

property is_debug: bool

Check if the application is in debug mode.

Returns:
bool: True if the application is in debug mode, False

otherwise.

property stage: ServerStage

Get the server stage.

Returns:

ServerStage: Server stage.