Applicationο
sanic.appο
- class sanic.app.Sanic(name=None, config=None, ctx=None, router=None, signal_router=None, error_handler=None, env_prefix='SANIC_', request_class=None, strict_slashes=False, log_config=None, configure_logging=True, dumps=None, loads=None, inspector=False, inspector_class=None, certloader_class=None)ο
Bases:
StaticHandleMixin
,BaseSanic
,StartupMixin
The main application instance
- Parameters:
name (Optional[str]) β
config (Optional[Config]) β
ctx (Optional[Any]) β
router (Optional[Router]) β
signal_router (Optional[SignalRouter]) β
error_handler (Optional[ErrorHandler]) β
env_prefix (Optional[str]) β
request_class (Optional[Type[Request]]) β
strict_slashes (bool) β
log_config (Optional[Dict[str, Any]]) β
configure_logging (bool) β
dumps (Optional[Callable[..., AnyStr]]) β
loads (Optional[Callable[..., Any]]) β
inspector (bool) β
inspector_class (Optional[Type[Inspector]]) β
certloader_class (Optional[Type[CertLoader]]) β
- add_route(handler, uri, methods=frozenset({'GET'}), host=None, strict_slashes=None, version=None, name=None, stream=False, version_prefix='/v', error_format=None, unquote=False, **ctx_kwargs)ο
A helper method to register class instance or functions as a handler to the application url routes.
- Parameters:
handler (Callable[[...], Coroutine[Any, Any, HTTPResponse | None]]) β function or class instance
uri (str) β path of the URL
methods (Iterable[str]) β list or tuple of methods allowed, these are overridden if using a HTTPMethodView
host (str | List[str] | None) β
strict_slashes (bool | None) β
version (int | str | float | None) β
name (str | None) β 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
ctx_kwargs (Any) β Keyword arguments that begin with a ctx_* prefix will be appended to the route context (
route.ctx
)error_format (str | None) β
unquote (bool) β
- Returns:
function or class instance
- Return type:
Callable[[β¦], Coroutine[Any, Any, HTTPResponse | None]]
- add_task(task, *, name=None, register=True)ο
Schedule a task to run later, after the loop has started. Different from asyncio.ensure_future in that it does not also return a future, and the actual ensure_future call is delayed until before server start.
See user guide re: background tasks
- Parameters:
task (Union[Future[Any], Coroutine[Any, Any, Any], Awaitable[Any]]) β future, coroutine or awaitable
name (Optional[str]) β
register (bool) β
- Return type:
Optional[Task[Any]]
- add_websocket_route(handler, uri, host=None, strict_slashes=None, subprotocols=None, version=None, name=None, version_prefix='/v', error_format=None, **ctx_kwargs)ο
A helper method to register a function as a websocket route.
- Parameters:
handler β a callable function or instance of a class that can handle the websocket request
host (str | List[str] | None) β Host IP or FQDN details
uri (str) β URL path that will be mapped to the websocket handler handler
strict_slashes (bool | None) β If the API endpoint needs to terminate with a β/β or not
subprotocols β Subprotocols to be used with websocket handshake
name (str | None) β A unique name assigned to the URL so that it can be used with
url_for()
version_prefix (str) β URL path that should be before the version value; default:
/v
ctx_kwargs (Any) β Keyword arguments that begin with a ctx_* prefix will be appended to the route context (
route.ctx
)version (int | str | float | None) β
error_format (str | None) β
- Returns:
Objected decorated by
websocket()
- amend()ο
If the application has started, this function allows changes to be made to add routes, middleware, and signals.
- Return type:
Iterator[None]
- blueprint(blueprint, **options)ο
Register a blueprint on the application.
- Parameters:
blueprint (Blueprint | Iterable[Blueprint] | BlueprintGroup) β Blueprint object or (list, tuple) thereof
options (Any) β option dictionary with blueprint defaults
- Returns:
Nothing
- async create_server(host=None, port=None, *, debug=False, ssl=None, sock=None, protocol=None, backlog=100, access_log=None, unix=None, return_asyncio_server=False, asyncio_server_kwargs=None, noisy_exceptions=None)ο
Asynchronous version of
run()
.This method will take care of the operations necessary to invoke the before_start events via
trigger_events()
method invocation before starting the sanic app in Async mode.Note
This does not support multiprocessing and is not the preferred way to run a
Sanic
application.- Parameters:
host (str) β Address to host on
port (int) β Port to host on
debug (bool) β Enables debug output (slows server)
ssl (SSLContext or dict) β SSLContext, or location of certificate and key for SSL encryption of worker(s)
sock (socket) β Socket for the server to accept connections from
protocol (type[Protocol]) β Subclass of asyncio Protocol class
backlog (int) β a number of unaccepted connections that the system will allow before refusing new connections
access_log (bool) β Enables writing access logs (slows server)
return_asyncio_server (bool) β flag that defines whether thereβs a need to return asyncio.Server or start it serving right away
asyncio_server_kwargs (dict) β key-value arguments for asyncio/uvloop create_server method
noisy_exceptions (bool) β Log exceptions that are normally considered to be quiet/silent
unix (str | None) β
- Returns:
AsyncioServer if return_asyncio_server is true, else Nothing
- Return type:
AsyncioServer | None
- delete(uri, host=None, strict_slashes=None, version=None, name=None, ignore_body=False, version_prefix='/v', error_format=None, **ctx_kwargs)ο
Add an API URL under the DELETE HTTP method
- Parameters:
uri (str) β URL to be tagged to DELETE method of HTTP
host (str | List[str] | None) β Host IP or FQDN for the service to use
strict_slashes (bool | None) β Instruct
Sanic
to check if the request URLs need to terminate with a /version (int | str | float | None) β API Version
name (str | None) β Unique name that can be used to identify the Route
version_prefix (str) β URL path that should be before the version value; default:
/v
ctx_kwargs (Any) β Keyword arguments that begin with a ctx_* prefix will be appended to the route context (
route.ctx
)ignore_body (bool) β
error_format (str | None) β
- Returns:
Object decorated with
route()
method- Return type:
Callable[[β¦], Coroutine[Any, Any, HTTPResponse | None]]
- enable_websocket(enable=True)ο
Enable or disable the support for websocket.
Websocket is enabled automatically if websocket routes are added to the application.
- exception(*exceptions, apply=True)ο
This method enables the process of creating a global exception handler for the current blueprint under question.
- Parameters:
args β List of Python exceptions to be caught by the handler
kwargs β Additional optional arguments to be passed to the exception handler
- :return a decorated method to handle global exceptions for any
route registered under this blueprint.
- get(uri, host=None, strict_slashes=None, version=None, name=None, ignore_body=True, version_prefix='/v', error_format=None, **ctx_kwargs)ο
Add an API URL under the GET HTTP method
- Parameters:
uri (str) β URL to be tagged to GET method of HTTP
host (str | List[str] | None) β Host IP or FQDN for the service to use
strict_slashes (bool | None) β Instruct
Sanic
to check if the request URLs need to terminate with a /version (int | str | float | None) β API Version
name (str | None) β Unique name that can be used to identify the Route
version_prefix (str) β URL path that should be before the version value; default:
/v
ctx_kwargs (Any) β Keyword arguments that begin with a ctx_* prefix will be appended to the route context (
route.ctx
)ignore_body (bool) β
error_format (str | None) β
- Returns:
Object decorated with
route()
method- Return type:
Callable[[β¦], Coroutine[Any, Any, HTTPResponse | None]]
- classmethod get_app(name=None, *, force_create=False)ο
Retrieve an instantiated Sanic instance
- Parameters:
name (str | None) β
force_create (bool) β
- Return type:
- async handle_exception(request, exception, run_middleware=True)ο
A handler that catches specific exceptions and outputs a response.
- Parameters:
request (Request) β The current request object
exception (BaseException) β The exception that was raised
run_middleware (bool) β
- Raises:
ServerError β response 500
- async handle_request(request)ο
Take a request from the HTTP Server and return a response object to be sent back The HTTP Server only expects a response object, so exception handling must be done here
- Parameters:
request (Request) β HTTP Request object
- Returns:
Nothing
- head(uri, host=None, strict_slashes=None, version=None, name=None, ignore_body=True, version_prefix='/v', error_format=None, **ctx_kwargs)ο
Add an API URL under the HEAD HTTP method
- Parameters:
uri (str) β URL to be tagged to HEAD method of HTTP
host (Optional[str], optional) β Host IP or FQDN for the service to use
strict_slashes (Optional[bool], optional) β Instruct
Sanic
to check if the request URLs need to terminate with a /version (Optional[str], optional) β API Version
name (Optional[str], optional) β Unique name that can be used to identify the Route
ignore_body (bool, optional) β whether the handler should ignore request body (eg. GET requests), defaults to True
version_prefix (str) β URL path that should be before the version value; default:
/v
ctx_kwargs (Any) β Keyword arguments that begin with a ctx_* prefix will be appended to the route context (
route.ctx
)error_format (str | None) β
- Returns:
Object decorated with
route()
method- Return type:
Callable[[β¦], Coroutine[Any, Any, HTTPResponse | None]]
- listener(listener_or_event, event_or_none=None, apply=True)ο
Create a listener from a decorated function.
To be used as a decorator:
@bp.listener("before_server_start") async def before_server_start(app, loop): ...
- Parameters:
event β event to listen to
listener_or_event (Callable[[Sanic], Coroutine[Any, Any, None] | None] | Callable[[Sanic, AbstractEventLoop], Coroutine[Any, Any, None] | None] | str) β
event_or_none (str | None) β
apply (bool) β
- Return type:
Callable[[Sanic], Coroutine[Any, Any, None] | None] | Callable[[Sanic, AbstractEventLoop], Coroutine[Any, Any, None] | None] | Callable[[Callable[[Sanic], Coroutine[Any, Any, None] | None] | Callable[[Sanic, AbstractEventLoop], Coroutine[Any, Any, None] | None]], Callable[[Sanic], Coroutine[Any, Any, None] | None] | Callable[[Sanic, AbstractEventLoop], Coroutine[Any, Any, None] | None]]
- middleware(middleware_or_request, attach_to='request', apply=True, *, priority=0)ο
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β).
- Param:
middleware_or_request: Optional parameter to use for identifying which type of middleware is being registered.
- on_request(middleware=None, *, priority=0)ο
Register a middleware to be called before a request is handled.
This is the same as @app.middleware(βrequestβ).
- Param:
middleware: A callable that takes in request.
- on_response(middleware=None, *, priority=0)ο
Register a middleware to be called after a response is created.
This is the same as @app.middleware(βresponseβ).
- Param:
middleware: A callable that takes in a request and its response.
- options(uri, host=None, strict_slashes=None, version=None, name=None, ignore_body=True, version_prefix='/v', error_format=None, **ctx_kwargs)ο
Add an API URL under the OPTIONS HTTP method
- Parameters:
uri (str) β URL to be tagged to OPTIONS method of HTTP
host (Optional[str], optional) β Host IP or FQDN for the service to use
strict_slashes (Optional[bool], optional) β Instruct
Sanic
to check if the request URLs need to terminate with a /version (Optional[str], optional) β API Version
name (Optional[str], optional) β Unique name that can be used to identify the Route
ignore_body (bool, optional) β whether the handler should ignore request body (eg. GET requests), defaults to True
version_prefix (str) β URL path that should be before the version value; default:
/v
ctx_kwargs (Any) β Keyword arguments that begin with a ctx_* prefix will be appended to the route context (
route.ctx
)error_format (str | None) β
- Returns:
Object decorated with
route()
method- Return type:
Callable[[β¦], Coroutine[Any, Any, HTTPResponse | None]]
- patch(uri, host=None, strict_slashes=None, stream=False, version=None, name=None, version_prefix='/v', error_format=None, **ctx_kwargs)ο
Add an API URL under the PATCH HTTP method
- Parameters:
uri (str) β URL to be tagged to PATCH method of HTTP
host (Optional[str], optional) β Host IP or FQDN for the service to use
strict_slashes (Optional[bool], optional) β Instruct
Sanic
to check if the request URLs need to terminate with a /stream (Optional[bool], optional) β whether to allow the request to stream its body
version (Optional[str], optional) β API Version
name (Optional[str], optional) β Unique name that can be used to identify the Route
ignore_body (bool, optional) β whether the handler should ignore request body (eg. GET requests), defaults to True
version_prefix (str) β URL path that should be before the version value; default:
/v
ctx_kwargs (Any) β Keyword arguments that begin with a ctx_* prefix will be appended to the route context (
route.ctx
)error_format (str | None) β
- Returns:
Object decorated with
route()
method- Return type:
Callable[[β¦], Coroutine[Any, Any, HTTPResponse | None]]
- post(uri, host=None, strict_slashes=None, stream=False, version=None, name=None, version_prefix='/v', error_format=None, **ctx_kwargs)ο
Add an API URL under the POST HTTP method
- Parameters:
uri (str) β URL to be tagged to POST method of HTTP
host (str | List[str] | None) β Host IP or FQDN for the service to use
strict_slashes (bool | None) β Instruct
Sanic
to check if the request URLs need to terminate with a /version (int | str | float | None) β API Version
name (str | None) β Unique name that can be used to identify the Route
version_prefix (str) β URL path that should be before the version value; default:
/v
ctx_kwargs (Any) β Keyword arguments that begin with a ctx_* prefix will be appended to the route context (
route.ctx
)stream (bool) β
error_format (str | None) β
- Returns:
Object decorated with
route()
method- Return type:
Callable[[β¦], Coroutine[Any, Any, HTTPResponse | None]]
- put(uri, host=None, strict_slashes=None, stream=False, version=None, name=None, version_prefix='/v', error_format=None, **ctx_kwargs)ο
Add an API URL under the PUT HTTP method
- Parameters:
uri (str) β URL to be tagged to PUT method of HTTP
host (str | List[str] | None) β Host IP or FQDN for the service to use
strict_slashes (bool | None) β Instruct
Sanic
to check if the request URLs need to terminate with a /version (int | str | float | None) β API Version
name (str | None) β Unique name that can be used to identify the Route
version_prefix (str) β URL path that should be before the version value; default:
/v
ctx_kwargs (Any) β Keyword arguments that begin with a ctx_* prefix will be appended to the route context (
route.ctx
)stream (bool) β
error_format (str | None) β
- Returns:
Object decorated with
route()
method- Return type:
Callable[[β¦], Coroutine[Any, Any, HTTPResponse | None]]
- classmethod register_app(app)ο
Register a Sanic instance
- Parameters:
app (Sanic) β
- Return type:
None
- register_listener(listener, event)ο
Register the listener for a given event.
- Parameters:
listener (Callable[[Sanic], Coroutine[Any, Any, None] | None] | Callable[[Sanic, AbstractEventLoop], Coroutine[Any, Any, None] | None]) β callable i.e. setup_db(app, loop)
event (str) β when to register listener i.e. βbefore_server_startβ
- Returns:
listener
- Return type:
Callable[[Sanic], Coroutine[Any, Any, None] | None] | Callable[[Sanic, AbstractEventLoop], Coroutine[Any, Any, None] | None]
- register_middleware(middleware, attach_to='request', *, priority=<sanic.helpers.Default object>)ο
Register an application level middleware that will be attached to all the API URLs registered under this application.
This method is internally invoked by the
middleware()
decorator provided at the app level.- Parameters:
middleware (Callable[[Request], HTTPResponse | None | Coroutine[Any, Any, HTTPResponse | None]] | Callable[[Request, BaseHTTPResponse], HTTPResponse | None | Coroutine[Any, Any, HTTPResponse | None]] | Middleware) β Callback method to be attached to the middleware
attach_to (str) β The state at which the middleware needs to be invoked in the lifecycle of an HTTP Request. request - Invoke before the request is processed response - Invoke before the response is returned back
priority (Default | int) β
- Returns:
decorated method
- Return type:
Callable[[Request], HTTPResponse | None | Coroutine[Any, Any, HTTPResponse | None]] | Callable[[Request, BaseHTTPResponse], HTTPResponse | None | Coroutine[Any, Any, HTTPResponse | None]] | Middleware
- register_named_middleware(middleware, route_names, attach_to='request', *, priority=<sanic.helpers.Default object>)ο
Method for attaching middleware to specific routes. This is mainly an internal tool for use by Blueprints to attach middleware to only its specific routes. But, it could be used in a more generalized fashion.
- Parameters:
middleware (Callable[[Request], HTTPResponse | None | Coroutine[Any, Any, HTTPResponse | None]] | Callable[[Request, BaseHTTPResponse], HTTPResponse | None | Coroutine[Any, Any, HTTPResponse | None]]) β the middleware to execute
route_names (Iterable[str]) β a list of the names of the endpoints
attach_to (str, optional) β whether to attach to request or response, defaults to βrequestβ
priority (Default | int) β
- route(uri, methods=None, host=None, strict_slashes=None, stream=False, version=None, name=None, ignore_body=False, apply=True, subprotocols=None, websocket=False, unquote=False, static=False, version_prefix='/v', error_format=None, **ctx_kwargs)ο
Decorate a function to be registered as a route
Example using context kwargs
@app.route(..., ctx_foo="foobar") async def route_handler(request: Request): assert request.route.ctx.foo == "foobar"
- Parameters:
uri (str) β path of the URL
methods (Iterable[str] | None) β list or tuple of methods allowed
host (str | List[str] | None) β the host, if required
strict_slashes (bool | None) β whether to apply strict slashes to the route
stream (bool) β whether to allow the request to stream its body
version (int | str | float | None) β route specific versioning
name (str | None) β user defined route name for url_for
ignore_body (bool) β whether the handler should ignore request body (eg. GET requests)
version_prefix (str) β URL path that should be before the version value; default:
/v
ctx_kwargs (Any) β Keyword arguments that begin with a ctx_* prefix will be appended to the route context (
route.ctx
)apply (bool) β
subprotocols (List[str] | None) β
websocket (bool) β
unquote (bool) β
static (bool) β
error_format (str | None) β
- Returns:
tuple of routes, decorated function
- Return type:
Callable[[Callable[[β¦], Coroutine[Any, Any, HTTPResponse | None]]], Callable[[β¦], Coroutine[Any, Any, HTTPResponse | None]] | Tuple[Route, Callable[[β¦], Coroutine[Any, Any, HTTPResponse | None]]]]
- run(host=None, port=None, *, dev=False, debug=False, auto_reload=None, version=HTTP.VERSION_1, ssl=None, sock=None, workers=1, protocol=None, backlog=100, register_sys_signals=True, access_log=None, unix=None, loop=None, reload_dir=None, noisy_exceptions=None, motd=True, fast=False, verbosity=0, motd_display=None, auto_tls=False, single_process=False)ο
Run the HTTP Server and listen until keyboard interrupt or term signal. On termination, drain connections before closing.
- Parameters:
host (str) β Address to host on
port (int) β Port to host on
debug (bool) β Enables debug output (slows server)
auto_reload (bool | None) β Reload app whenever its source code is changed. Enabled by default in debug mode.
ssl (str, dict, SSLContext or list) β SSLContext, or location of certificate and key for SSL encryption of worker(s)
sock (socket) β Socket for the server to accept connections from
workers (int) β Number of processes received before it is respected
protocol (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 (bool) β Enables writing access logs (slows server)
unix (str) β Unix socket to listen on instead of TCP port
noisy_exceptions (bool) β Log exceptions that are normally considered to be quiet/silent
dev (bool) β
version (HTTP | Literal[1] | ~typing.Literal[3]) β
loop (AbstractEventLoop | None) β
reload_dir (str | List[str] | None) β
motd (bool) β
fast (bool) β
verbosity (int) β
motd_display (Dict[str, str] | None) β
auto_tls (bool) β
single_process (bool) β
- Returns:
Nothing
- Return type:
None
- signal(event, *, apply=True, condition=None, exclusive=True)ο
For creating a signal handler, used similar to a route handler:
@app.signal("foo.bar.<thing>") async def signal_handler(thing, **kwargs): print(f"[signal_handler] {thing=}", kwargs)
- Parameters:
event (str) β Representation of the event in
one.two.three
formapply (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 (bool) β 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
- Return type:
Callable[[Callable[[β¦], Coroutine[Any, Any, None]]], Callable[[β¦], Coroutine[Any, Any, None]]]
- static(uri, file_or_directory, pattern='/?.+', use_modified_since=True, use_content_range=False, stream_large_files=False, name='static', host=None, strict_slashes=None, content_type=None, apply=True, resource_type=None, index=None, directory_view=False, directory_handler=None)ο
Register a root to serve files from. The input can either be a file or a directory. This method will enable an easy and simple way to setup the
Route
necessary to serve the static files.- Parameters:
uri (str) β URL path to be used for serving static content
file_or_directory (PathLike | str) β Path for the Static file/directory with static files
pattern (str) β Regex Pattern identifying the valid static files
use_modified_since (bool) β If true, send file modified time, and return not modified if the browserβs matches the serverβs
use_content_range (bool) β If true, process header for range requests and sends the file part that is requested
stream_large_files (bool | int) β If true, use the
StreamingHTTPResponse.file_stream()
handler rather than theHTTPResponse.file()
handler to send the file. If this is an integer, this represents the threshold size to switch toStreamingHTTPResponse.file_stream()
name (str) β user defined name used for url_for
host (str | None) β Host IP or FQDN for the service to use
strict_slashes (bool | None) β Instruct
Sanic
to check if the request URLs need to terminate with a /content_type (str | None) β user defined content type for header
apply (bool) β If true, will register the route immediately
resource_type (str | None) β Explicitly declare a resource to be a β fileβ or a βdirβ
index (str | Sequence[str] | None) β When exposing against a directory, index is the name that will be served as the default file. When multiple files 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
directory_handler (DirectoryHandler | None) β An instance of
DirectoryHandler
that can be used for explicitly controlling and subclassing the behavior of the default directory handler
- Returns:
routes registered on the router
- Return type:
List[sanic.router.Route]
- stop(terminate=True, unregister=False)ο
This kills the Sanic
- Parameters:
terminate (bool) β
unregister (bool) β
- classmethod unregister_app(app)ο
Unregister a Sanic instance
- Parameters:
app (Sanic) β
- Return type:
None
- update_config(config)ο
Update app.config. Full implementation can be found in the user guide.
See user guide re: configuration
- Parameters:
config (bytes | str | dict | Any) β
- url_for(view_name, **kwargs)ο
Build a URL based on a view name and the values provided.
In order to build a URL, all request parameters must be supplied as keyword arguments, and each parameter must pass the test for the specified parameter type. If these conditions are not met, a URLBuildError will be thrown.
Keyword arguments that are not request parameters will be included in the output URLβs query string.
There are several _special_ keyword arguments that will alter how the URL will be returned:
_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 (only applies with_external=True
)_server:
str
- If not using_host
, this will be used for defining the hostname of the URL (only applies with_external=True
), defaults toapp.config.SERVER_NAME
If you want the PORT to appear in your URL, you should set it in:
app.config.SERVER_NAME = "myserver:7777"
- Parameters:
view_name (str) β string referencing the view name
kwargs β keys and values that are used to build request parameters and query string arguments.
- Returns:
the built URL
- Raises:
URLBuildError
- websocket(uri, host=None, strict_slashes=None, subprotocols=None, version=None, name=None, apply=True, version_prefix='/v', error_format=None, **ctx_kwargs)ο
Decorate a function to be registered as a websocket route
- Parameters:
uri (str) β path of the URL
host (str | List[str] | None) β Host IP or FQDN details
strict_slashes (bool | None) β If the API endpoint needs to terminate with a β/β or not
subprotocols (List[str] | None) β optional list of str with supported subprotocols
name (str | None) β A unique name assigned to the URL so that it can be used with
url_for()
version_prefix (str) β URL path that should be before the version value; default:
/v
ctx_kwargs (Any) β Keyword arguments that begin with a ctx_* prefix will be appended to the route context (
route.ctx
)version (int | str | float | None) β
apply (bool) β
error_format (str | None) β
- Returns:
tuple of routes, decorated function
- property asgi_clientο
A testing client that uses ASGI to reach into the application to execute handlers.
- Returns:
testing client
- Return type:
SanicASGITestClient
- property loopο
Synonymous with asyncio.get_event_loop().
Note
Only supported when using the app.run method.
- property m: WorkerMultiplexerο
Interface for interacting with the worker processes
- property state: ApplicationStateο
- Returns:
The application state
sanic.configο
- class sanic.config.Config(defaults=None, env_prefix='SANIC_', keep_alive=None, *, converters=None)ο
Bases:
dict
- Parameters:
defaults (Optional[Dict[str, Union[str, bool, int, float, None]]]) β
env_prefix (Optional[str]) β
keep_alive (Optional[bool]) β
converters (Optional[Sequence[Callable[[str], Any]]]) β
- load(config)ο
Update app.config.
Note
Only upper case settings are considered
You can upload app config by providing path to py file holding settings.
# /some/py/file A = 1 B = 2
config.update_config("${some}/py/file")
Yes you can put environment variable here, but they must be provided in format:
${some_env_var}
, and mark that$some_env_var
is treated as plain string.You can upload app config by providing dict holding settings.
d = {"A": 1, "B": 2} config.update_config(d)
You can upload app config by providing any object holding settings, but in such case config.__dict__ will be used as dict holding settings.
class C: A = 1 B = 2 config.update_config(C)
- Parameters:
config (bytes | str | dict | Any) β
- load_environment_vars(prefix='SANIC_')ο
Looks for prefixed environment variables and applies them to the configuration if present. This is called automatically when Sanic starts up to load environment variables into config. Environment variables should start with the defined prefix and should only contain uppercase letters.
It will automatically hydrate the following types:
int
float
bool
Anything else will be imported as a
str
. If you would like to add additional types to this list, you can usesanic.config.Config.register_type()
. Just make sure that they are registered before you instantiate your application.class Foo: def __init__(self, name) -> None: self.name = name config = Config(converters=[Foo]) app = Sanic(__name__, config=config)
- register_type(converter)ο
Allows for adding custom function to cast from a string value to any other type. The function should raise ValueError if it is not the correct type.
- Parameters:
converter (Callable[[str], Any]) β
- Return type:
None
- update([E, ]**F) None. Update D from dict/iterable E and F. ο
If E is present and has a .keys() method, then does: for k in E: D[k] = E[k] If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v In either case, this is followed by: for k in F: D[k] = F[k]
- Parameters:
other (Any) β
kwargs (Any) β
- Return type:
None
- update_config(config)ο
Update app.config.
Note
Only upper case settings are considered
You can upload app config by providing path to py file holding settings.
# /some/py/file A = 1 B = 2
config.update_config("${some}/py/file")
Yes you can put environment variable here, but they must be provided in format:
${some_env_var}
, and mark that$some_env_var
is treated as plain string.You can upload app config by providing dict holding settings.
d = {"A": 1, "B": 2} config.update_config(d)
You can upload app config by providing any object holding settings, but in such case config.__dict__ will be used as dict holding settings.
class C: A = 1 B = 2 config.update_config(C)
- Parameters:
config (bytes | str | dict | Any) β
- class sanic.config.DescriptorMeta(name, bases, namespace, **kwargs)ο
Bases:
ABCMeta
sanic.application.constantsο
- enum sanic.application.constants.Mode(value)ο
Bases:
StrEnum
An enumeration.
- Member Type:
str
Valid values are as follows:
- PRODUCTION = <Mode.PRODUCTION: 'production'>ο
- DEBUG = <Mode.DEBUG: 'debug'>ο
sanic.application.stateο
- class sanic.application.state.ApplicationServerInfo(settings: 'Dict[str, Any]', stage: 'ServerStage' = <ServerStage.STOPPED: 1>, server: 'Optional[AsyncioServer]' = None)ο
Bases:
object
- Parameters:
settings (Dict[str, Any]) β
stage (ServerStage) β
server (AsyncioServer | None) β
- class sanic.application.state.ApplicationState(app: 'Sanic', asgi: 'bool' = False, coffee: 'bool' = False, fast: 'bool' = False, host: 'str' = '', port: 'int' = 0, ssl: 'Optional[SSLContext]' = None, sock: 'Optional[socket]' = None, unix: 'Optional[str]' = None, mode: 'Mode' = <Mode.PRODUCTION: 'production'>, reload_dirs: 'Set[Path]' = <factory>, auto_reload: 'bool' = False, server: 'Server' = <Server.SANIC: 'sanic'>, is_running: 'bool' = False, is_started: 'bool' = False, is_stopping: 'bool' = False, verbosity: 'int' = 0, workers: 'int' = 0, primary: 'bool' = True, server_info: 'List[ApplicationServerInfo]' = <factory>, _init: 'bool' = False)ο
Bases:
object
- Parameters:
app (Sanic) β
asgi (bool) β
coffee (bool) β
fast (bool) β
host (str) β
port (int) β
ssl (Optional[SSLContext]) β
sock (Optional[socket]) β
unix (Optional[str]) β
mode (Mode) β
reload_dirs (Set[Path]) β
auto_reload (bool) β
server (Server) β
is_running (bool) β
is_started (bool) β
is_stopping (bool) β
verbosity (int) β
workers (int) β
primary (bool) β
server_info (List[ApplicationServerInfo]) β
_init (bool) β