Table of Contents
Sanicsanic.appsanic.app.Sanic#
The main application instance
class Sanic(name: str, config: Optional[config_type] = None, ctx: Optional[ctx_type] = None, router: Optional[Router] = None, signal_router: Optional[SignalRouter] = None, error_handler: Optional[ErrorHandler] = None, env_prefix: Optional[str] = SANIC_, request_class: Optional[Type[Request]] = None, strict_slashes: bool = False, log_config: Optional[Dict[str, Any]] = None, configure_logging: bool = True, dumps: Optional[Callable[..., AnyStr]] = None, loads: Optional[Callable[..., Any]] = None, inspector: bool = False, inspector_class: Optional[Type[Inspector]] = None, certloader_class: Optional[Type[CertLoader]] = None): -> None
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 (-
).
# will cause an error because it contains spaces
Sanic("This is not legal")
# this is legal
Sanic("Hyphens-are-legal_or_also_underscores")
Parameters
- 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.
def ack(self): -> None
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.
add_route#
A helper method to register class-based view or functions as a handler to the application url routes.
def add_route(self, handler: typing.Callable[..., typing.Coroutine[typing.Any, typing.Any, typing.Optional[sanic.response.types.HTTPResponse]]], uri: <class 'str'>, methods: typing.Iterable[str] = frozenset({'GET'}), host: typing.Union[str, typing.List[str], NoneType] = None, strict_slashes: typing.Optional[bool] = None, version: typing.Union[int, str, float, NoneType] = None, name: typing.Optional[str] = None, stream: <class 'bool'> = False, version_prefix: <class 'str'> = /v, error_format: typing.Optional[str] = None, unquote: <class 'bool'> = False, ctx_kwargs: typing.Any): -> typing.Callable[..., typing.Coroutine[typing.Any, typing.Any, typing.Optional[sanic.response.types.HTTPResponse]]]
Parameters
- 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.
Return
- RouteHandler
The route handler.
Examples
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).
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)
add_signal#
Registers a signal handler for a specific event.
def add_signal(self, handler: Optional[Callable[..., Any]], event: Union[str, Enum], condition: Optional[Dict[str, Any]] = None, exclusive: bool = True): -> Callable[..., Any]
Parameters
- 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 thecondition
has been met. This is inapplicable to blueprint signals, which are ALWAYS non-exclusive. Defaults toTrue
.
Return
- Callable[..., Any]
The handler that was registered.
add_task#
Schedule a task to run later, after the loop has started.
def add_task(self, task: Union[Future[Any], Coroutine[Any, Any, Any], Awaitable[Any]], name: Optional[str] = None, register: bool = True): -> Optional[Task[Any]]
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.
Parameters
- task
Union[Future[Any], Coroutine[Any, Any, Any], Awaitable[Any]] The future, coroutine, or awaitable to schedule.
- name
Optional[str] The name of the task, if needed for later reference. Defaults to
None
.
- register
bool Whether to register the task. Defaults to
True
.
Return
- Optional[Task[Any]]
The task that was scheduled, if applicable.
add_websocket_route#
A helper method to register a function as a websocket route.
def add_websocket_route(self, handler, uri: <class 'str'>, host: typing.Union[str, typing.List[str], NoneType] = None, strict_slashes: typing.Optional[bool] = None, subprotocols = None, version: typing.Union[int, str, float, NoneType] = None, name: typing.Optional[str] = None, version_prefix: <class 'str'> = /v, error_format: typing.Optional[str] = None, ctx_kwargs: typing.Any)
Parameters
- 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
).
Return
- Callable
Object passed as the handler.
after_reload_trigger#
Decorator for registering a listener for the after_reload_trigger event.
def after_reload_trigger(self, listener: typing.Union[typing.Callable[[~Sanic], typing.Optional[typing.Coroutine[typing.Any, typing.Any, NoneType]]], typing.Callable[[~Sanic, asyncio.events.AbstractEventLoop], typing.Optional[typing.Coroutine[typing.Any, typing.Any, NoneType]]], NoneType], priority: <class 'int'> = 0): -> typing.Union[typing.Callable[[~Sanic], typing.Optional[typing.Coroutine[typing.Any, typing.Any, NoneType]]], typing.Callable[[~Sanic, asyncio.events.AbstractEventLoop], typing.Optional[typing.Coroutine[typing.Any, typing.Any, NoneType]]]]
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 for more details.
Parameters
- listener
ListenerType[Sanic] The listener handler to attach.
Examples
@app.after_reload_trigger
async def on_after_reload_trigger(app: Sanic, changed: set[str]):
print("After reload trigger, changed files: ", changed)
after_server_start#
Decorator for registering a listener for the after_server_start event.
def after_server_start(self, listener: typing.Union[typing.Callable[[~Sanic], typing.Optional[typing.Coroutine[typing.Any, typing.Any, NoneType]]], typing.Callable[[~Sanic, asyncio.events.AbstractEventLoop], typing.Optional[typing.Coroutine[typing.Any, typing.Any, NoneType]]], NoneType], priority: <class 'int'> = 0): -> typing.Union[typing.Callable[[~Sanic], typing.Optional[typing.Coroutine[typing.Any, typing.Any, NoneType]]], typing.Callable[[~Sanic, asyncio.events.AbstractEventLoop], typing.Optional[typing.Coroutine[typing.Any, typing.Any, NoneType]]]]
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 for more details.
Parameters
- listener
ListenerType[Sanic] The listener handler to attach.
Examples
@app.after_server_start
async def on_after_server_start(app: Sanic):
print("After server start")
after_server_stop#
Decorator for registering a listener for the after_server_stop event.
def after_server_stop(self, listener: typing.Union[typing.Callable[[~Sanic], typing.Optional[typing.Coroutine[typing.Any, typing.Any, NoneType]]], typing.Callable[[~Sanic, asyncio.events.AbstractEventLoop], typing.Optional[typing.Coroutine[typing.Any, typing.Any, NoneType]]], NoneType], priority: <class 'int'> = 0): -> typing.Union[typing.Callable[[~Sanic], typing.Optional[typing.Coroutine[typing.Any, typing.Any, NoneType]]], typing.Callable[[~Sanic, asyncio.events.AbstractEventLoop], typing.Optional[typing.Coroutine[typing.Any, typing.Any, NoneType]]]]
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 for more details.
Parameters
- listener
ListenerType[Sanic] The listener handler to attach.
Examples
@app.after_server_stop
async def on_after_server_stop(app: Sanic):
print("After server stop")
all_exceptions#
Enables the process of creating a global exception handler as a convenience.
def all_exceptions(self, handler: typing.Callable[..., typing.Any]): -> typing.Callable[..., typing.Any]
This following two examples are equivalent:
@app.exception(Exception)
async def handler(request: Request, exception: Exception) -> HTTPResponse:
return text(f"Exception raised: {exception}")
@app.all_exceptions
async def handler(request: Request, exception: Exception) -> HTTPResponse:
return text(f"Exception raised: {exception}")
Parameters
- handler
Callable[..., Any] A coroutine function to handle exceptions.
Return
- Callable[..., Any]
A decorated method to handle global exceptions for any route registered under this blueprint.
amend#
Context manager to allow changes to the app after it has started.
def amend(self): -> Iterator[None]
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.
Examples
with app.amend():
app.add_route(handler, '/new_route')
asgi_client#
A testing client that uses ASGI to reach into the application to execute handlers.
@property
def asgi_client(self): -> 'SanicASGITestClient'
This property is available if the sanic-testing
package is installed.
See Test Clients for details.
Return
- SanicASGITestClient
A testing client from the
sanic-testing
package.
before_reload_trigger#
Decorator for registering a listener for the before_reload_trigger event.
def before_reload_trigger(self, listener: typing.Union[typing.Callable[[~Sanic], typing.Optional[typing.Coroutine[typing.Any, typing.Any, NoneType]]], typing.Callable[[~Sanic, asyncio.events.AbstractEventLoop], typing.Optional[typing.Coroutine[typing.Any, typing.Any, NoneType]]], NoneType], priority: <class 'int'> = 0): -> typing.Union[typing.Callable[[~Sanic], typing.Optional[typing.Coroutine[typing.Any, typing.Any, NoneType]]], typing.Callable[[~Sanic, asyncio.events.AbstractEventLoop], typing.Optional[typing.Coroutine[typing.Any, typing.Any, NoneType]]]]
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 for more details.
Parameters
- listener
ListenerType[Sanic] The listener handler to attach.
Examples
@app.before_reload_trigger
async def on_before_reload_trigger(app: Sanic):
print("Before reload trigger")
before_server_start#
Decorator for registering a listener for the before_server_start event.
def before_server_start(self, listener: typing.Union[typing.Callable[[~Sanic], typing.Optional[typing.Coroutine[typing.Any, typing.Any, NoneType]]], typing.Callable[[~Sanic, asyncio.events.AbstractEventLoop], typing.Optional[typing.Coroutine[typing.Any, typing.Any, NoneType]]], NoneType] = None, priority: <class 'int'> = 0): -> typing.Union[typing.Callable[[~Sanic], typing.Optional[typing.Coroutine[typing.Any, typing.Any, NoneType]]], typing.Callable[[~Sanic, asyncio.events.AbstractEventLoop], typing.Optional[typing.Coroutine[typing.Any, typing.Any, NoneType]]]]
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 for more details.
Parameters
- listener
ListenerType[Sanic] The listener handler to attach.
Examples
@app.before_server_start
async def on_before_server_start(app: Sanic):
print("Before server start")
before_server_stop#
Decorator for registering a listener for the before_server_stop event.
def before_server_stop(self, listener: typing.Union[typing.Callable[[~Sanic], typing.Optional[typing.Coroutine[typing.Any, typing.Any, NoneType]]], typing.Callable[[~Sanic, asyncio.events.AbstractEventLoop], typing.Optional[typing.Coroutine[typing.Any, typing.Any, NoneType]]], NoneType], priority: <class 'int'> = 0): -> typing.Union[typing.Callable[[~Sanic], typing.Optional[typing.Coroutine[typing.Any, typing.Any, NoneType]]], typing.Callable[[~Sanic, asyncio.events.AbstractEventLoop], typing.Optional[typing.Coroutine[typing.Any, typing.Any, NoneType]]]]
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 for more details.
Parameters
- listener
ListenerType[Sanic] The listener handler to attach.
Examples
@app.before_server_stop
async def on_before_server_stop(app: Sanic):
print("Before server stop")
blueprint#
Register a blueprint on the application.
def blueprint(self, blueprint: Union[Blueprint, Iterable[Blueprint], BlueprintGroup], url_prefix: Optional[str] = None, version: Optional[Union[int, float, str]] = None, strict_slashes: Optional[bool] = None, version_prefix: Optional[str] = None, name_prefix: Optional[str] = None): -> None
See Blueprints for more information.
Parameters
- 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
.
Examples
app = Sanic("TestApp")
bp = Blueprint('TestBP')
@bp.route('/route')
def handler(request):
return text('Hello, Blueprint!')
app.blueprint(bp, url_prefix='/blueprint')
cancel_task#
Cancel a named task.
async def cancel_task(self, name: str, msg: Optional[str] = None, raise_exception: bool = True): -> None
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.
Parameters
- 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.
Examples
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!")
catch_exception#
Register an exception handler for logging or processing.
def catch_exception(self, handler: Callable[[SignalMixin, Exception], Coroutine[Any, Any, None]]): -> None
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.
Parameters
- 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.
Examples
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.
create_server#
Low level API for creating a Sanic Server instance.
async def create_server(self, host: Optional[str] = None, port: Optional[int] = None, debug: bool = False, ssl: Union[None, SSLContext, dict, str, list, tuple] = None, sock: Optional[socket] = None, protocol: Optional[Type[Protocol]] = None, backlog: int = 100, access_log: Optional[bool] = None, unix: Optional[str] = None, return_asyncio_server: bool = True, asyncio_server_kwargs: Optional[Dict[str, Any]] = None, noisy_exceptions: Optional[bool] = None): -> Optional[AsyncioServer]
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.
Parameters
- 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.
Return
- Optional[AsyncioServer]
AsyncioServer if
return_asyncio_server
isTrue
elseNone
.
Examples
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())
delete#
Decorate a function handler to create a route definition using the DELETE HTTP method.
def delete(self, uri: <class 'str'>, host: typing.Union[str, typing.List[str], NoneType] = None, strict_slashes: typing.Optional[bool] = None, version: typing.Union[int, str, float, NoneType] = None, name: typing.Optional[str] = None, ignore_body: <class 'bool'> = False, version_prefix: <class 'str'> = /v, error_format: typing.Optional[str] = None, ctx_kwargs: typing.Any): -> typing.Callable[..., typing.Coroutine[typing.Any, typing.Any, typing.Optional[sanic.response.types.HTTPResponse]]]
Parameters
- 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
).
Return
- RouteHandler
Object decorated with route method.
dispatch#
Dispatches an event to the signal router.
def dispatch(self, event: str, condition: Optional[Dict[str, str]] = None, context: Optional[Dict[str, Any]] = None, fail_not_found: bool = True, inline: bool = False, reverse: bool = False): -> Coroutine[Any, Any, Awaitable[Union[Task, Any]]]
Parameters
- 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. IfFalse
, returns aTask
. Default isFalse
.
- reverse
bool Whether to reverse the dispatch order. Default is
False
.
Return
- Coroutine[Any, Any, Awaitable[Union[Task, Any]]]
An awaitable that returns the result directly if
inline=True
, or aTask
ifinline=False
.
Examples
@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}
})
dispatch_delayed_tasks#
Signal handler for dispatching delayed tasks.
@staticmethod
async def dispatch_delayed_tasks(app: Sanic, loop: AbstractEventLoop): -> None
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.
Parameters
- app
Sanic The Sanic application instance.
- loop
AbstractEventLoop The event loop in which the tasks are being run.
enable_websocket#
Enable or disable the support for websocket.
def enable_websocket(self, enable: bool = True): -> None
Websocket is enabled automatically if websocket routes are added to the application. This typically will not need to be called manually.
Parameters
- enable
bool If set to
True
, enables websocket support. If set toFalse
, disables websocket support. Defaults toTrue
.
event#
Wait for a specific event to be triggered.
async def event(self, event: Union[str, Enum], timeout: Optional[Union[int, float]] = None, condition: Optional[Dict[str, Any]] = None, exclusive: bool = True): -> None
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
.
app.config.EVENT_AUTOREGISTER = True
Parameters
- 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.
Examples
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))
exception#
Decorator used to register an exception handler for the current application or blueprint instance.
def exception(self, exceptions: typing.Union[typing.Type[Exception], typing.List[typing.Type[Exception]]], apply: <class 'bool'> = True): -> typing.Callable
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 for more information.
Parameters
- exceptions
Union[Type[Exception], List[Type[Exception]]] List of Python exceptions to be caught by the handler.
- apply
bool Whether the exception handler should be applied. Defaults to True.
Return
- Callable
A decorated method to handle global exceptions for any route registered under this blueprint.
Examples
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)
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}")
ext#
Convenience property for accessing Sanic Extensions.
@property
def ext(self): -> Extend
This property is available if the sanic-ext
package is installed.
See Sanic Extensions for details.
Return
- Extend
The Sanic Extensions instance.
Examples
A typical use case might be for registering a dependency injection.
app.ext.dependency(SomeObject())
extend#
Extend Sanic with additional functionality using Sanic Extensions.
def extend(self, extensions: Optional[List[Type[Extension]]] = None, built_in_extensions: bool = True, config: Optional[Union[Config, Dict[str, Any]]] = None, kwargs): -> Extend
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 for details.
Parameters
- extensions
Optional[List[Type[Extension]]] A list of extensions to add. Defaults to
None
, meaning only built-in extensions are added.
- built_in_extensions
bool Whether to enable built-in extensions. Defaults to
True
.
- config
Optional[Union[Config, Dict[str, Any]]] Optional custom configuration for the extensions. Defaults to
None
.
- **kwargs
Additional keyword arguments that might be needed by specific extensions.
Return
- 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.
app.extend(
extensions=[MyCustomExtension],
built_in_extensions=True
)
finalize#
Finalize the routing configuration for the Sanic application.
def finalize(self): -> None
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.
Examples
app.finalize()
finalize_middleware#
Finalize the middleware configuration for the Sanic application.
def finalize_middleware(self): -> None
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.
Examples
app.finalize_middleware()
get#
Decorate a function handler to create a route definition using the GET HTTP method.
def get(self, uri: <class 'str'>, host: typing.Union[str, typing.List[str], NoneType] = None, strict_slashes: typing.Optional[bool] = None, version: typing.Union[int, str, float, NoneType] = None, name: typing.Optional[str] = None, ignore_body: <class 'bool'> = True, version_prefix: <class 'str'> = /v, error_format: typing.Optional[str] = None, ctx_kwargs: typing.Any): -> typing.Callable[..., typing.Coroutine[typing.Any, typing.Any, typing.Optional[sanic.response.types.HTTPResponse]]]
Parameters
- 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
).
Return
- RouteHandler
Object decorated with route method.
get_address#
Retrieve the host address and port, with default values based on the given parameters.
def get_address(host: Optional[str], port: Optional[int], version: HTTPVersion = 1, auto_tls: bool = False): -> Tuple[str, int]
Parameters
- 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 orauto_tls=True
, else8000
- version
HTTPVersion HTTP Version. Defaults to
HTTP.VERSION_1
(HTTP/1.1).
- auto_tls
bool Automatic TLS flag. Defaults to
False
.
Return
- Tuple[str, int]
Tuple containing the host and port
get_app#
Retrieve an instantiated Sanic instance by name.
@classmethod
def get_app(name: Optional[str] = None, force_create: bool = False): -> Sanic
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.
def setup_routes():
app = Sanic.get_app()
app.add_route(handler_1, '/route1')
app.add_route(handler_2, '/route2')
Parameters
- name
Optional[str] 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 If
True
and the named app does not exist, a new instance will be created. Defaults toFalse
.
Return
- 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.
Examples
app1 = Sanic("app1")
app2 = Sanic.get_app("app1") # app2 is the same instance as app1
get_motd_data#
Retrieves the message of the day (MOTD) data.
def get_motd_data(self, server_settings: Optional[Dict[str, Any]] = None): -> Tuple[Dict[str, Any], Dict[str, Any]]
Parameters
- server_settings
Optional[Dict[str, Any]] Settings for the server. Defaults to
None
.
Return
- Tuple[Dict[str, Any], Dict[str, Any]]
A tuple containing two dictionaries with the relevant MOTD data.
get_server_location#
Using the server settings, retrieve the server location.
def get_server_location(server_settings: Optional[Dict[str, Any]] = None): -> str
Parameters
- server_settings
Optional[Dict[str, Any]] Settings for the server. Defaults to
None
.
Return
- str
The server location.
get_task#
Get a named task.
def get_task(self, name: str, raise_exception: bool = True): -> Optional[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.
Parameters
- 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 toTrue
.
Return
- Optional[Task]
The task, if found.
handle_exception#
A handler that catches specific exceptions and outputs a response.
async def handle_exception(self, request: <class 'sanic.request.types.Request'>, exception: <class 'BaseException'>, run_middleware: <class 'bool'> = True): -> None
Note
This method is typically used internally, and you should not need to call it directly.
Parameters
- 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.
handle_request#
Handles a request by dispatching it to the appropriate handler.
async def handle_request(self, request: <class 'sanic.request.types.Request'>): -> None
Note
This method is typically used internally, and you should not need to call it directly.
Parameters
- request
Request The current request object.
Raises
- ServerError
response 500.
head#
Decorate a function handler to create a route definition using the HEAD HTTP method.
def head(self, uri: <class 'str'>, host: typing.Union[str, typing.List[str], NoneType] = None, strict_slashes: typing.Optional[bool] = None, version: typing.Union[int, str, float, NoneType] = None, name: typing.Optional[str] = None, ignore_body: <class 'bool'> = True, version_prefix: <class 'str'> = /v, error_format: typing.Optional[str] = None, ctx_kwargs: typing.Any): -> typing.Callable[..., typing.Coroutine[typing.Any, typing.Any, typing.Optional[sanic.response.types.HTTPResponse]]]
Parameters
- 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
).
Return
- RouteHandler
Object decorated with route method.
inspector#
An instance of Inspector for accessing the application's state.
@property
def inspector(self): -> Inspector
This can only be accessed from a worker process, and only if the inspector has been enabled.
See Inspector for details.
Return
- Inspector
An instance of Inspector.
listener#
Create a listener for a specific event in the application's lifecycle.
def listener(self, listener_or_event: typing.Union[typing.Callable[[~Sanic], typing.Optional[typing.Coroutine[typing.Any, typing.Any, NoneType]]], typing.Callable[[~Sanic, asyncio.events.AbstractEventLoop], typing.Optional[typing.Coroutine[typing.Any, typing.Any, NoneType]]], str], event_or_none: typing.Optional[str] = None, apply: <class 'bool'> = True, priority: <class 'int'> = 0): -> typing.Union[typing.Callable[[~Sanic], typing.Optional[typing.Coroutine[typing.Any, typing.Any, NoneType]]], typing.Callable[[~Sanic, asyncio.events.AbstractEventLoop], typing.Optional[typing.Coroutine[typing.Any, typing.Any, NoneType]]], typing.Callable[[typing.Union[typing.Callable[[~Sanic], typing.Optional[typing.Coroutine[typing.Any, typing.Any, NoneType]]], typing.Callable[[~Sanic, asyncio.events.AbstractEventLoop], typing.Optional[typing.Coroutine[typing.Any, typing.Any, NoneType]]]]], typing.Union[typing.Callable[[~Sanic], typing.Optional[typing.Coroutine[typing.Any, typing.Any, NoneType]]], typing.Callable[[~Sanic, asyncio.events.AbstractEventLoop], typing.Optional[typing.Coroutine[typing.Any, typing.Any, NoneType]]]]]]
See 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.
@app.before_server_start
async def prefered_method(_):
...
@app.listener("before_server_start")
async def not_prefered_method(_):
...
Parameters
- 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 toNone
.
- apply
bool Whether to apply the listener immediately. Defaults to
True
.
- priority
int The priority of the listener. Defaults to
0
.
Return
- Union[ListenerType[Sanic], Callable[[ListenerType[Sanic]], ListenerType[Sanic]]]
The listener or a callable that takes a listener.
Examples
The following code snippet shows how you can use this method as a decorator:
@bp.listener("before_server_start")
async def before_server_start(app, loop):
...
loop#
Synonymous with asyncio.get_event_loop().
@property
def loop(self): -> AbstractEventLoop
Note
Only supported when using the app.run
method.
Return
- AbstractEventLoop
The event loop for the application.
Raises
- SanicException
If the application is not running.
m#
Interface for interacting with the worker processes
@property
def m(self): -> WorkerMultiplexer
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 for more information.
Return
- WorkerMultiplexer
The worker multiplexer instance
Examples
app.m.restart() # restarts the worker
app.m.terminate() # terminates the worker
app.m.scale(4) # scales the number of workers to 4
main_process_ready#
Decorator for registering a listener for the main_process_ready event.
def main_process_ready(self, listener: typing.Union[typing.Callable[[~Sanic], typing.Optional[typing.Coroutine[typing.Any, typing.Any, NoneType]]], typing.Callable[[~Sanic, asyncio.events.AbstractEventLoop], typing.Optional[typing.Coroutine[typing.Any, typing.Any, NoneType]]], NoneType], priority: <class 'int'> = 0): -> typing.Union[typing.Callable[[~Sanic], typing.Optional[typing.Coroutine[typing.Any, typing.Any, NoneType]]], typing.Callable[[~Sanic, asyncio.events.AbstractEventLoop], typing.Optional[typing.Coroutine[typing.Any, typing.Any, NoneType]]]]
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 and Listeners for more details.
Parameters
- listener
ListenerType[Sanic] The listener handler to attach.
Examples
@app.main_process_ready
async def on_main_process_ready(app: Sanic):
print("Main process ready")
main_process_start#
Decorator for registering a listener for the main_process_start event.
def main_process_start(self, listener: typing.Union[typing.Callable[[~Sanic], typing.Optional[typing.Coroutine[typing.Any, typing.Any, NoneType]]], typing.Callable[[~Sanic, asyncio.events.AbstractEventLoop], typing.Optional[typing.Coroutine[typing.Any, typing.Any, NoneType]]], NoneType], priority: <class 'int'> = 0): -> typing.Union[typing.Callable[[~Sanic], typing.Optional[typing.Coroutine[typing.Any, typing.Any, NoneType]]], typing.Callable[[~Sanic, asyncio.events.AbstractEventLoop], typing.Optional[typing.Coroutine[typing.Any, typing.Any, NoneType]]]]
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 for more details.
Parameters
- listener
ListenerType[Sanic] The listener handler to attach.
Examples
@app.main_process_start
async def on_main_process_start(app: Sanic):
print("Main process started")
main_process_stop#
Decorator for registering a listener for the main_process_stop event.
def main_process_stop(self, listener: typing.Union[typing.Callable[[~Sanic], typing.Optional[typing.Coroutine[typing.Any, typing.Any, NoneType]]], typing.Callable[[~Sanic, asyncio.events.AbstractEventLoop], typing.Optional[typing.Coroutine[typing.Any, typing.Any, NoneType]]], NoneType], priority: <class 'int'> = 0): -> typing.Union[typing.Callable[[~Sanic], typing.Optional[typing.Coroutine[typing.Any, typing.Any, NoneType]]], typing.Callable[[~Sanic, asyncio.events.AbstractEventLoop], typing.Optional[typing.Coroutine[typing.Any, typing.Any, NoneType]]]]
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 for more details.
Parameters
- listener
ListenerType[Sanic] The listener handler to attach.
Examples
@app.main_process_stop
async def on_main_process_stop(app: Sanic):
print("Main process stopped")
make_coffee#
Try for yourself! sanic server:app --coffee
def make_coffee(self, args, kwargs)
▄████████▄
██ ██▀▀▄
███████████ █
███████████▄▄▀
▀███████▀
manager#
Property to access the WorkerManager instance.
@property
def manager(self): -> WorkerManager
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 for details.
Return
- 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.
Examples
app.manager.manage(...)
middleware#
Decorator for registering middleware.
def middleware(self, middleware_or_request: typing.Union[typing.Callable[[~Request], typing.Union[sanic.response.types.HTTPResponse, NoneType, typing.Coroutine[typing.Any, typing.Any, typing.Optional[sanic.response.types.HTTPResponse]]]], typing.Callable[[~Request, sanic.response.types.BaseHTTPResponse], typing.Union[sanic.response.types.HTTPResponse, NoneType, typing.Coroutine[typing.Any, typing.Any, typing.Optional[sanic.response.types.HTTPResponse]]]], str], attach_to: <class 'str'> = request, apply: <class 'bool'> = True, priority: <class 'int'> = 0): -> typing.Union[typing.Callable[[~Request], typing.Union[sanic.response.types.HTTPResponse, NoneType, typing.Coroutine[typing.Any, typing.Any, typing.Optional[sanic.response.types.HTTPResponse]]]], typing.Callable[[~Request, sanic.response.types.BaseHTTPResponse], typing.Union[sanic.response.types.HTTPResponse, NoneType, typing.Coroutine[typing.Any, typing.Any, typing.Optional[sanic.response.types.HTTPResponse]]]], typing.Callable[[typing.Union[typing.Callable[[~Request], typing.Union[sanic.response.types.HTTPResponse, NoneType, typing.Coroutine[typing.Any, typing.Any, typing.Optional[sanic.response.types.HTTPResponse]]]], typing.Callable[[~Request, sanic.response.types.BaseHTTPResponse], typing.Union[sanic.response.types.HTTPResponse, NoneType, typing.Coroutine[typing.Any, typing.Any, typing.Optional[sanic.response.types.HTTPResponse]]]]]], typing.Union[typing.Callable[[~Request], typing.Union[sanic.response.types.HTTPResponse, NoneType, typing.Coroutine[typing.Any, typing.Any, typing.Optional[sanic.response.types.HTTPResponse]]]], typing.Callable[[~Request, sanic.response.types.BaseHTTPResponse], typing.Union[sanic.response.types.HTTPResponse, NoneType, typing.Coroutine[typing.Any, typing.Any, typing.Optional[sanic.response.types.HTTPResponse]]]]]]]
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 for more information.
Parameters
- middleware_or_request
Union[Callable, str] Middleware function or the keyword 'request' or 'response'.
- attach_to
str When to apply the middleware; either 'request' (before the request is handled) or 'response' (after the response is created). Defaults to
'request'
.
- apply
bool Whether the middleware should be applied. Defaults to
True
.
- priority
int The priority level of the middleware. Lower numbers are executed first. Defaults to
0
.
Return
- Union[Callable, Callable[[Callable], Callable]]
The decorated middleware function or a partial function depending on how the method was called.
Examples
@app.middleware('request')
async def custom_middleware(request):
...
motd#
Outputs the message of the day (MOTD).
def motd(self, server_settings: Optional[Dict[str, Any]] = None): -> None
It generally can only be called once per process, and is usually
called by the run
method in the main process.
Parameters
- server_settings
Optional[Dict[str, Any]] Settings for the server. Defaults to
None
.
on_request#
Register a middleware to be called before a request is handled.
def on_request(self, middleware = None, priority = 0): -> typing.Union[typing.Callable[[~Request], typing.Union[sanic.response.types.HTTPResponse, NoneType, typing.Coroutine[typing.Any, typing.Any, typing.Optional[sanic.response.types.HTTPResponse]]]], typing.Callable[[~Request, sanic.response.types.BaseHTTPResponse], typing.Union[sanic.response.types.HTTPResponse, NoneType, typing.Coroutine[typing.Any, typing.Any, typing.Optional[sanic.response.types.HTTPResponse]]]]]
This is the same as @app.middleware('request').
Parameters
- middleware
Callable A callable that takes in a request. Defaults to
None
.
Return
- Callable
The decorated middleware function or a partial function depending on how the method was called.
Examples
@app.on_request
async def custom_middleware(request):
request.ctx.custom = 'value'
on_response#
Register a middleware to be called after a response is created.
def on_response(self, middleware = None, priority = 0)
This is the same as @app.middleware('response').
Parameters
- middleware
Callable A callable that takes in a request and response. Defaults to
None
.
Return
- Callable
The decorated middleware function or a partial function depending on how the method was called.
Examples
@app.on_response
async def custom_middleware(request, response):
response.headers['X-Server'] = 'Sanic'
options#
Decorate a function handler to create a route definition using the OPTIONS HTTP method.
def options(self, uri: <class 'str'>, host: typing.Union[str, typing.List[str], NoneType] = None, strict_slashes: typing.Optional[bool] = None, version: typing.Union[int, str, float, NoneType] = None, name: typing.Optional[str] = None, ignore_body: <class 'bool'> = True, version_prefix: <class 'str'> = /v, error_format: typing.Optional[str] = None, ctx_kwargs: typing.Any): -> typing.Callable[..., typing.Coroutine[typing.Any, typing.Any, typing.Optional[sanic.response.types.HTTPResponse]]]
Parameters
- 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
).
Return
- RouteHandler
Object decorated with route method.
patch#
Decorate a function handler to create a route definition using the PATCH HTTP method.
def patch(self, uri: <class 'str'>, host: typing.Union[str, typing.List[str], NoneType] = None, strict_slashes: typing.Optional[bool] = None, stream = False, version: typing.Union[int, str, float, NoneType] = None, name: typing.Optional[str] = None, version_prefix: <class 'str'> = /v, error_format: typing.Optional[str] = None, ctx_kwargs: typing.Any): -> typing.Callable[..., typing.Coroutine[typing.Any, typing.Any, typing.Optional[sanic.response.types.HTTPResponse]]]
Parameters
- 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 toFalse
.
- 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
).
Return
- RouteHandler
Object decorated with route method.
post#
Decorate a function handler to create a route definition using the POST HTTP method.
def post(self, uri: <class 'str'>, host: typing.Union[str, typing.List[str], NoneType] = None, strict_slashes: typing.Optional[bool] = None, stream: <class 'bool'> = False, version: typing.Union[int, str, float, NoneType] = None, name: typing.Optional[str] = None, version_prefix: <class 'str'> = /v, error_format: typing.Optional[str] = None, ctx_kwargs: typing.Any): -> typing.Callable[..., typing.Coroutine[typing.Any, typing.Any, typing.Optional[sanic.response.types.HTTPResponse]]]
Parameters
- 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
).
Return
- RouteHandler
Object decorated with route method.
prepare#
Prepares one or more Sanic applications to be served simultaneously.
def prepare(self, host: Optional[str] = None, port: Optional[int] = None, dev: bool = False, debug: bool = False, auto_reload: Optional[bool] = None, version: HTTPVersion = 1, ssl: Union[None, SSLContext, dict, str, list, tuple] = None, sock: Optional[socket] = None, workers: int = 1, protocol: Optional[Type[Protocol]] = None, backlog: int = 100, register_sys_signals: bool = True, access_log: Optional[bool] = None, unix: Optional[str] = None, loop: Optional[AbstractEventLoop] = None, reload_dir: Optional[Union[List[str], str]] = None, noisy_exceptions: Optional[bool] = None, motd: bool = True, fast: bool = False, verbosity: int = 0, motd_display: Optional[Dict[str, str]] = None, coffee: bool = False, auto_tls: bool = False, single_process: bool = False): -> None
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.
Parameters
- host
Optional[str] Hostname to listen on. Defaults to
None
.
- port
Optional[int] Port to listen on. Defaults to
None
.
- dev
bool Development mode. Defaults to
False
.
- debug
bool Debug mode. Defaults to
False
.
- auto_reload
Optional[bool] Auto reload feature. Defaults to
None
.
- version
HTTPVersion HTTP version to use. Defaults to
HTTP.VERSION_1
.
- ssl
Union[None, SSLContext, dict, str, list, tuple] SSL configuration. Defaults to
None
.
- sock
Optional[socket] Socket to bind to. Defaults to
None
.
- workers
int Number of worker processes. Defaults to
1
.
- protocol
Optional[Type[Protocol]] Custom protocol class. Defaults to
None
.
- backlog
int Maximum number of pending connections. Defaults to
100
.
- register_sys_signals
bool Register system signals. Defaults to
True
.
- access_log
Optional[bool] Access log. Defaults to
None
.
- unix
Optional[str] Unix socket. Defaults to
None
.
- loop
Optional[AbstractEventLoop] Event loop. Defaults to
None
.
- reload_dir
Optional[Union[List[str], str]] Reload directory. Defaults to
None
.
- noisy_exceptions
Optional[bool] Display exceptions. Defaults to
None
.
- motd
bool Display message of the day. Defaults to
True
.
- fast
bool Fast mode. Defaults to
False
.
- verbosity
int Verbosity level. Defaults to
0
.
- motd_display
Optional[Dict[str, str]] Custom MOTD display. Defaults to
None
.
- coffee
bool Coffee mode. Defaults to
False
.
- auto_tls
bool Auto TLS. Defaults to
False
.
- single_process
bool 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
andworkers
.
- RuntimeError
Raised when attempting to use
single_process
withfast
,workers
, orauto_reload
.
- TypeError
Raised when attempting to use
loop
withcreate_server
.
- ValueError
Raised when
PROXIES_COUNT
is negative.
Examples
if __name__ == "__main__":
app.prepare()
app.serve()
purge_tasks#
Purges completed and cancelled tasks from the task registry.
def purge_tasks(self): -> None
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.
put#
Decorate a function handler to create a route definition using the PUT HTTP method.
def put(self, uri: <class 'str'>, host: typing.Union[str, typing.List[str], NoneType] = None, strict_slashes: typing.Optional[bool] = None, stream: <class 'bool'> = False, version: typing.Union[int, str, float, NoneType] = None, name: typing.Optional[str] = None, version_prefix: <class 'str'> = /v, error_format: typing.Optional[str] = None, ctx_kwargs: typing.Any): -> typing.Callable[..., typing.Coroutine[typing.Any, typing.Any, typing.Optional[sanic.response.types.HTTPResponse]]]
Parameters
- 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
).
Return
- RouteHandler
Object decorated with route method.
refresh#
Refresh the application instance. This is used internally by Sanic.
def refresh(self, passthru: Optional[Dict[str, Any]] = None): -> Sanic
Warning
This method is intended for internal use only and should not be called directly.
Parameters
- passthru
Optional[Dict[str, Any]] Optional dictionary of attributes to pass through to the new instance. Defaults to
None
.
Return
- Sanic
The refreshed application instance.
register_app#
Register a Sanic instance with the class registry.
@classmethod
def register_app(app: Sanic): -> None
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.
Parameters
- 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
Sanic.register_app(my_app)
register_listener#
Register the listener for a given event.
def register_listener(self, listener: ListenerType[SanicVar], event: str, priority: int = 0): -> ListenerType[SanicVar]
Parameters
- listener
Callable The listener to register.
- event
str The event to listen for.
Return
- Callable
The listener that was registered.
register_middleware#
Register a middleware to be called before a request is handled.
def register_middleware(self, middleware: Union[MiddlewareType, Middleware], attach_to: str = "request", priority: Union[Default, int] = <Default>): -> Union[MiddlewareType, Middleware]
Parameters
- 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
.
Return
- Union[Callable, Callable[[Callable], Callable]]
The decorated middleware function or a partial function depending on how the method was called.
register_named_middleware#
Used to register named middleqare (middleware typically on blueprints)
def register_named_middleware(self, middleware: MiddlewareType, route_names: Iterable[str], attach_to: str = "request", priority: Union[Default, int] = <Default>)
Parameters
- 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
.
Return
- Union[Callable, Callable[[Callable], Callable]]
The decorated middleware function or a partial function depending on how the method was called.
reload_dirs#
The directories that are monitored for auto-reload.
@property
def reload_dirs(self): -> Set[Path]
Return
- Set[str]
The set of directories that are monitored for auto-reload.
reload_process_start#
Decorator for registering a listener for the reload_process_start event.
def reload_process_start(self, listener: typing.Union[typing.Callable[[~Sanic], typing.Optional[typing.Coroutine[typing.Any, typing.Any, NoneType]]], typing.Callable[[~Sanic, asyncio.events.AbstractEventLoop], typing.Optional[typing.Coroutine[typing.Any, typing.Any, NoneType]]], NoneType], priority: <class 'int'> = 0): -> typing.Union[typing.Callable[[~Sanic], typing.Optional[typing.Coroutine[typing.Any, typing.Any, NoneType]]], typing.Callable[[~Sanic, asyncio.events.AbstractEventLoop], typing.Optional[typing.Coroutine[typing.Any, typing.Any, NoneType]]]]
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 for more details.
Parameters
- listener
ListenerType[Sanic] The listener handler to attach.
Examples
@app.reload_process_start
async def on_reload_process_start(app: Sanic):
print("Reload process started")
reload_process_stop#
Decorator for registering a listener for the reload_process_stop event.
def reload_process_stop(self, listener: typing.Union[typing.Callable[[~Sanic], typing.Optional[typing.Coroutine[typing.Any, typing.Any, NoneType]]], typing.Callable[[~Sanic, asyncio.events.AbstractEventLoop], typing.Optional[typing.Coroutine[typing.Any, typing.Any, NoneType]]], NoneType], priority: <class 'int'> = 0): -> typing.Union[typing.Callable[[~Sanic], typing.Optional[typing.Coroutine[typing.Any, typing.Any, NoneType]]], typing.Callable[[~Sanic, asyncio.events.AbstractEventLoop], typing.Optional[typing.Coroutine[typing.Any, typing.Any, NoneType]]]]
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 for more details.
Parameters
- listener
ListenerType[Sanic] The listener handler to attach.
Examples
@app.reload_process_stop
async def on_reload_process_stop(app: Sanic):
print("Reload process stopped")
report_exception#
Register a handler to report exceptions.
def report_exception(self, handler: Callable[[Sanic, Exception], Coroutine[Any, Any, None]]): -> Callable[[Exception], Coroutine[Any, Any, None]]
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:
@app.signal(Event.SERVER_EXCEPTION_REPORT)
async def report(exception):
await do_something_with_error(exception)
Parameters
- handler
Callable[[Sanic, Exception], Coroutine[Any, Any, None]] The handler to register.
Return
- Callable[[Sanic, Exception], Coroutine[Any, Any, None]]
The handler that was registered.
route#
Decorate a function to be registered as a route.
def route(self, uri: <class 'str'>, methods: typing.Optional[typing.Iterable[str]] = None, host: typing.Union[str, typing.List[str], NoneType] = None, strict_slashes: typing.Optional[bool] = None, stream: <class 'bool'> = False, version: typing.Union[int, str, float, NoneType] = None, name: typing.Optional[str] = None, ignore_body: <class 'bool'> = False, apply: <class 'bool'> = True, subprotocols: typing.Optional[typing.List[str]] = None, websocket: <class 'bool'> = False, unquote: <class 'bool'> = False, static: <class 'bool'> = False, version_prefix: <class 'str'> = /v, error_format: typing.Optional[str] = None, ctx_kwargs: typing.Any): -> typing.Callable[[typing.Callable[..., typing.Coroutine[typing.Any, typing.Any, typing.Optional[sanic.response.types.HTTPResponse]]]], typing.Union[typing.Callable[..., typing.Coroutine[typing.Any, typing.Any, typing.Optional[sanic.response.types.HTTPResponse]]], typing.Tuple[sanic_routing.route.Route, typing.Callable[..., typing.Coroutine[typing.Any, typing.Any, typing.Optional[sanic.response.types.HTTPResponse]]]]]]
Parameters
- 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
).
Return
- RouteWrapper
Tuple of routes, decorated function.
Examples
Using the method to define a GET endpoint:
@app.route("/hello")
async def hello(request: Request):
return text("Hello, World!")
Adding context kwargs to the route:
@app.route("/greet", ctx_name="World")
async def greet(request: Request):
name = request.route.ctx.name
return text(f"Hello, {name}!")
run#
Run the HTTP Server and listen until keyboard interrupt or term signal. On termination, drain connections before closing.
def run(self, host: Optional[str] = None, port: Optional[int] = None, dev: bool = False, debug: bool = False, auto_reload: Optional[bool] = None, version: HTTPVersion = 1, ssl: Union[None, SSLContext, dict, str, list, tuple] = None, sock: Optional[socket] = None, workers: int = 1, protocol: Optional[Type[Protocol]] = None, backlog: int = 100, register_sys_signals: bool = True, access_log: Optional[bool] = None, unix: Optional[str] = None, loop: Optional[AbstractEventLoop] = None, reload_dir: Optional[Union[List[str], str]] = None, noisy_exceptions: Optional[bool] = None, motd: bool = True, fast: bool = False, verbosity: int = 0, motd_display: Optional[Dict[str, str]] = None, auto_tls: bool = False, single_process: bool = False): -> None
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:
sanic server:app`
If you are using this method to run Sanic, make sure you do the following:
- Use
if __name__ == "__main__"
to guard the code. - Do NOT define the app instance inside the
if
block.
See Dynamic Applications for more information about the second point.
Parameters
- 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.
Raises
- RuntimeError
Raised when attempting to serve HTTP/3 as a secondary server.
- RuntimeError
Raised when attempting to use both
fast
andworkers
.
- RuntimeError
Raised when attempting to use
single_process
withfast
,workers
, orauto_reload
.
- TypeError
Raised when attempting to use
loop
withcreate_server
.
- ValueError
Raised when
PROXIES_COUNT
is negative.
Examples
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)
run_delayed_task#
Executes a delayed task within the context of a given app and loop.
@staticmethod
async def run_delayed_task(app: Sanic, loop: AbstractEventLoop, task: Task[Any]): -> None
This method prepares a given task by invoking the app's private
_prep_task
method and then awaits the execution of the prepared task.
Parameters
- 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.
serve#
Serve one or more Sanic applications.
def serve(primary: Optional[Sanic] = None, app_loader: Optional[AppLoader] = None, factory: Optional[Callable[[], Sanic]] = None): -> None
This is the main entry point for running Sanic applications. It
should be called in the if __name__ == "__main__"
block.
Parameters
- primary
Optional[Sanic] The primary Sanic application to serve. Defaults to
None
.
- app_loader
Optional[AppLoader] An AppLoader instance to use for loading applications. Defaults to
None
.
- factory
Optional[Callable[[], Sanic]] 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
withcreate_server
.
- RuntimeError
Raised when attempting to use
single_process
withfast
,workers
, orauto_reload
.
- RuntimeError
Raised when attempting to serve HTTP/3 as a secondary server.
- RuntimeError
Raised when attempting to use both
fast
andworkers
.
- TypeError
Raised when attempting to use
loop
withcreate_server
.
- ValueError
Raised when
PROXIES_COUNT
is negative.
Examples
if __name__ == "__main__":
app.prepare()
Sanic.serve()
serve_location#
Retrieve the server location.
@property
def serve_location(self): -> str
Return
- str
The server location.
serve_single#
Serve a single process of a Sanic application.
def serve_single(primary: Optional[Sanic] = None): -> None
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:
sanic app.sanic:app --single-process
Or, if you need to do it programmatically, you should use the
single_process
argument of run
:
app.run(single_process=True)
Parameters
- primary
Optional[Sanic] 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
andworkers
.
- ValueError
Raised when
PROXIES_COUNT
is negative.
set_serving#
Set the serving state of the application.
def set_serving(self, serving: bool): -> None
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.
Parameters
- serving
bool Whether the application is serving.
setup_loop#
Set up the event loop.
def setup_loop(self): -> None
An internal method that sets up the event loop to uvloop if possible, or a Windows selector loop if on Windows.
should_auto_reload#
Check if any applications have auto-reload enabled.
def should_auto_reload(): -> bool
Return
- bool
True
if any applications have auto-reload enabled, elseFalse
.
shutdown_tasks#
Cancel all tasks except the server task.
def shutdown_tasks(self, timeout: Optional[float] = None, increment: float = 0.1): -> None
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.
Parameters
- 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
.
signal#
For creating a signal handler, used similar to a route handler:
def signal(self, event: Union[str, Enum], apply: bool = True, condition: Optional[Dict[str, Any]] = None, exclusive: bool = True, priority: int = 0): -> Callable[[SignalHandler], SignalHandler]
@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 toNone
- exclusive
When
True
, the signal can only be dispatched when the condition has been met. WhenFalse
, the signal can be dispatched either with or without it. THIS IS INAPPLICABLE TO BLUEPRINT SIGNALS. THEY ARE ALWAYS NON-EXCLUSIVE, defaults toTrue
signalize#
Finalize the signal handling configuration for the Sanic application.
def signalize(self, allow_fail_builtin: bool = True): -> None
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.
Parameters
- allow_fail_builtin
bool If set to
True
, will allow built-in signals to fail during the finalization process. Defaults toTrue
.
Raises
- FinalizationError
If there is an error during the signal finalization process, and the application is not in test mode.
Examples
app.signalize(allow_fail_builtin=False)
state#
The application state.
@property
def state(self): -> ApplicationState
Return
- ApplicationState
The current state of the application.
static#
Register a root to serve files from. The input can either be a file or a directory.
def static(self, uri: <class 'str'>, file_or_directory: typing.Union[os.PathLike, str], pattern: <class 'str'> = /?.+, use_modified_since: <class 'bool'> = True, use_content_range: <class 'bool'> = False, stream_large_files: typing.Union[bool, int] = False, name: <class 'str'> = static, host: typing.Optional[str] = None, strict_slashes: typing.Optional[bool] = None, content_type: typing.Optional[str] = None, apply: <class 'bool'> = True, resource_type: typing.Optional[str] = None, index: typing.Union[str, typing.Sequence[str], NoneType] = None, directory_view: <class 'bool'> = False, directory_handler: typing.Optional[sanic.handlers.directory.DirectoryHandler] = None)
This method provides an easy and simple way to set up the route necessary to serve static files.
Parameters
- 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 Regex pattern identifying the valid static files. Defaults to
r"/?.+"
.
- use_modified_since
bool 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 If true, process header for range requests and sends the file part that is requested. Defaults to
False
.
- stream_large_files
Union[bool, int] If
True
, use theStreamingHTTPResponse.file_stream
handler rather than theHTTPResponse.file handler
to send the file. If this is an integer, it represents the threshold size to switch toStreamingHTTPResponse.file_stream
. Defaults toFalse
, which means that the response will not be streamed.
- name
str User-defined name used for url_for. Defaults to
"static"
.
- host
Optional[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 slash.
- content_type
Optional[str] User-defined content type for header.
- apply
bool If true, will register the route immediately. Defaults to
True
.
- resource_type
Optional[str] Explicitly declare a resource to be a
"file"
or a"dir"
.
- index
Optional[Union[str, Sequence[str]]] 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 Whether to fallback to showing the directory viewer when exposing a directory. Defaults to
False
.
- directory_handler
Optional[DirectoryHandler] An instance of DirectoryHandler that can be used for explicitly controlling and subclassing the behavior of the default directory handler.
Return
- List[sanic.router.Route]
Routes registered on the router.
Examples
Serving a single file:
app.static('/foo', 'path/to/static/file.txt')
Serving all files from a directory:
app.static('/static', 'path/to/static/directory')
Serving large files with a specific threshold:
app.static('/static', 'path/to/large/files', stream_large_files=1000000)
stop#
This kills the Sanic server, cleaning up after itself.
def stop(self, terminate: bool = True, unregister: bool = False): -> None
Parameters
- terminate
bool Force kill all requests immediately without allowing them to finish processing.
- unregister
bool Unregister the app from the global registry.
tasks#
The tasks that are currently registered with the application.
@property
def tasks(self): -> Iterable[Task[Any]]
Return
- Iterable[Task[Any]]
The tasks that are currently registered with the application.
test_client#
A testing client that uses httpx and a live running server to reach into the application to execute handlers.
@property
def test_client(self): -> 'SanicTestClient'
This property is available if the sanic-testing
package is installed.
See Test Clients for details.
Return
- SanicTestClient
A testing client from the
sanic-testing
package.
unregister_app#
Unregister a Sanic instance from the class registry.
@classmethod
def unregister_app(app: Sanic): -> None
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.
Parameters
- app
Sanic The Sanic instance to be unregistered.
Raises
- SanicException
If the app is not an instance of Sanic.
Examples
Sanic.unregister_app(my_app)
update_config#
Update the application configuration.
def update_config(self, config: Union[bytes, str, dict, Any]): -> None
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 for details.
Parameters
- config
Union[bytes, str, dict, Any] The configuration object, dictionary, or path to a configuration file.
url_for#
Build a URL based on a view name and the values provided.
def url_for(self, view_name: str, kwargs)
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
Parameters
- 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.
Return
- str
The built URL.
Raises
- URLBuildError
If there are issues with constructing the URL.
Examples
Building a URL for a specific view with parameters:
url_for('view_name', param1='value1', param2='value2')
# /view-name?param1=value1¶m2=value2
Creating an external URL with a specific scheme and anchor:
url_for('view_name', _scheme='https', _external=True, _anchor='section1')
# https://example.com/view-name#section1
Creating a URL with a specific host:
url_for('view_name', _host='subdomain.example.com')
# http://subdomain.example.com/view-name
websocket#
Decorate a function to be registered as a websocket route.
def websocket(self, uri: <class 'str'>, host: typing.Union[str, typing.List[str], NoneType] = None, strict_slashes: typing.Optional[bool] = None, subprotocols: typing.Optional[typing.List[str]] = None, version: typing.Union[int, str, float, NoneType] = None, name: typing.Optional[str] = None, apply: <class 'bool'> = True, version_prefix: <class 'str'> = /v, error_format: typing.Optional[str] = None, ctx_kwargs: typing.Any)
Parameters
- 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
).
Return
- tuple
Tuple of routes, decorated function.