Table of Contents
BaseMixinsanic.mixins.baseExceptionMixinsanic.mixins.exceptionsListenerEventsanic.mixins.listenersListenerMixinsanic.mixins.listenersMiddlewareMixinsanic.mixins.middlewareRouteMixinsanic.mixins.routesSignalMixinsanic.mixins.signalsStartupMixinsanic.mixins.startupStaticHandleMixinsanic.mixins.staticStaticMixinsanic.mixins.staticsanic.mixins.exceptions.ExceptionMixin#
class ExceptionMixin(args, kwargs): -> None
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.
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}")
sanic.mixins.listeners.ListenerEvent#
str(object='') -> str
class ListenerEvent(value, names = None, module = None, qualname = None, type = None, start = 1, boundary = None)
str(bytes_or_buffer[, encoding[, errors]]) -> str
Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to sys.getdefaultencoding(). errors defaults to 'strict'.
sanic.mixins.listeners.ListenerMixin#
class ListenerMixin(args, kwargs): -> None
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")
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")
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):
...
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")
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")
sanic.mixins.middleware.MiddlewareMixin#
class MiddlewareMixin(args, kwargs): -> None
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()
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):
...
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'
sanic.mixins.routes.RouteMixin#
Base class for some other mixins.
class RouteMixin(args, kwargs): -> None
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_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.
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.
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.
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.
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.
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.
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}!")
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.
sanic.mixins.signals.SignalMixin#
class SignalMixin(args, kwargs): -> None
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.
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.
event#
def event(self, event: str)
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
sanic.mixins.startup.StartupMixin#
class StartupMixin()
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())
get_address#
Retrieve the host address and port, with default values based on the given parameters.
@staticmethod
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_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.
@staticmethod
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.
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
make_coffee#
Try for yourself! sanic server:app --coffee
def make_coffee(self, args, kwargs)
▄████████▄
██ ██▀▀▄
███████████ █
███████████▄▄▀
▀███████▀
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
.
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()
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)
serve#
Serve one or more Sanic applications.
@classmethod
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.
@classmethod
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.
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.
@classmethod
def should_auto_reload(): -> bool
Return
- bool
True
if any applications have auto-reload enabled, elseFalse
.
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.
sanic.mixins.static.StaticHandleMixin#
class StaticHandleMixin()
sanic.mixins.static.StaticMixin#
Base class for some other mixins.
class StaticMixin(args, kwargs): -> None
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)