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)ο
Bases:
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]]) β
- 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, Optional[HTTPResponse]]]) β 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 (Optional[Union[str, List[str]]]) β
strict_slashes (Optional[bool]) β
version (Optional[Union[int, str, float]]) β
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
ctx_kwargs (Any) β Keyword arguments that begin with a ctx_* prefix will be appended to the route context (
route.ctx
)error_format (Optional[str]) β
unquote (bool) β
- Returns
function or class instance
- Return type
Callable[[β¦], Coroutine[Any, Any, Optional[HTTPResponse]]]
- 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 (Optional[Union[str, List[str]]]) β Host IP or FQDN details
uri (str) β URL path that will be mapped to the websocket handler handler
strict_slashes (Optional[bool]) β If the API endpoint needs to terminate with a β/β or not
subprotocols β Subprotocols to be used with websocket handshake
name (Optional[str]) β 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 (Optional[Union[int, str, float]]) β
error_format (Optional[str]) β
- Returns
Objected decorated by
websocket()
- blueprint(blueprint, **options)ο
Register a blueprint on the application.
- Parameters
blueprint (Union[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 (Optional[str]) β
- Returns
AsyncioServer if return_asyncio_server is true, else Nothing
- Return type
Optional[AsyncioServer]
- delete(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 DELETE HTTP method
- Parameters
uri (str) β URL to be tagged to 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
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 (Optional[str]) β
- Returns
Object decorated with
route()
method- Return type
Callable[[β¦], Coroutine[Any, Any, Optional[HTTPResponse]]]
- 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 (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
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 (Optional[str]) β
- Returns
Object decorated with
route()
method- Return type
Callable[[β¦], Coroutine[Any, Any, Optional[HTTPResponse]]]
- classmethod get_app(name=None, *, force_create=False)ο
Retrieve an instantiated Sanic instance
- Parameters
name (Optional[str]) β
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 (Optional[str]) β
- Returns
Object decorated with
route()
method- Return type
Callable[[β¦], Coroutine[Any, Any, Optional[HTTPResponse]]]
- 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 (Union[Callable[[Sanic], Optional[Coroutine[Any, Any, None]]], Callable[[Sanic, AbstractEventLoop], Optional[Coroutine[Any, Any, None]]], str]) β
event_or_none (Optional[str]) β
apply (bool) β
- Return type
Union[Callable[[Sanic], Optional[Coroutine[Any, Any, None]]], Callable[[Sanic, AbstractEventLoop], Optional[Coroutine[Any, Any, None]]], Callable[[Union[Callable[[Sanic], Optional[Coroutine[Any, Any, None]]], Callable[[Sanic, AbstractEventLoop], Optional[Coroutine[Any, Any, None]]]]], Union[Callable[[Sanic], Optional[Coroutine[Any, Any, None]]], Callable[[Sanic, AbstractEventLoop], Optional[Coroutine[Any, Any, 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 (Optional[str]) β
- Returns
Object decorated with
route()
method- Return type
Callable[[β¦], Coroutine[Any, Any, Optional[HTTPResponse]]]
- 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 (Optional[str]) β
- Returns
Object decorated with
route()
method- Return type
Callable[[β¦], Coroutine[Any, Any, Optional[HTTPResponse]]]
- 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 (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
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 (Optional[str]) β
- Returns
Object decorated with
route()
method- Return type
Callable[[β¦], Coroutine[Any, Any, Optional[HTTPResponse]]]
- 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 (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
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 (Optional[str]) β
- Returns
Object decorated with
route()
method- Return type
Callable[[β¦], Coroutine[Any, Any, Optional[HTTPResponse]]]
- 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 (Union[Callable[[Sanic], Optional[Coroutine[Any, Any, None]]], Callable[[Sanic, AbstractEventLoop], Optional[Coroutine[Any, Any, None]]]]) β callable i.e. setup_db(app, loop)
event (str) β when to register listener i.e. βbefore_server_startβ
- Returns
listener
- Return type
Union[Callable[[Sanic], Optional[Coroutine[Any, Any, None]]], Callable[[Sanic, AbstractEventLoop], Optional[Coroutine[Any, Any, 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 (Union[Callable[[Request], Union[HTTPResponse, None, Coroutine[Any, Any, Optional[HTTPResponse]]]], Callable[[Request, BaseHTTPResponse], Union[HTTPResponse, None, Coroutine[Any, Any, Optional[HTTPResponse]]]], 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 (Union[Default, int]) β
- Returns
decorated method
- Return type
Union[Callable[[Request], Union[HTTPResponse, None, Coroutine[Any, Any, Optional[HTTPResponse]]]], Callable[[Request, BaseHTTPResponse], Union[HTTPResponse, None, Coroutine[Any, Any, Optional[HTTPResponse]]]], 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 (Union[Callable[[Request], Union[HTTPResponse, None, Coroutine[Any, Any, Optional[HTTPResponse]]]], Callable[[Request, BaseHTTPResponse], Union[HTTPResponse, None, Coroutine[Any, Any, Optional[HTTPResponse]]]]]) β 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 (Union[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 (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 (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 (Optional[List[str]]) β
websocket (bool) β
unquote (bool) β
static (bool) β
error_format (Optional[str]) β
- Returns
tuple of routes, decorated function
- Return type
Callable[[Callable[[β¦], Coroutine[Any, Any, Optional[HTTPResponse]]]], Union[Callable[[β¦], Coroutine[Any, Any, Optional[HTTPResponse]]], Tuple[Route, Callable[[β¦], Coroutine[Any, Any, Optional[HTTPResponse]]]]]]
- 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, legacy=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 (Optional[bool]) β 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 (Union[HTTP, Literal[1], ~typing.Literal[3]]) β
loop (Optional[AbstractEventLoop]) β
reload_dir (Optional[Union[str, List[str]]]) β
motd (bool) β
fast (bool) β
verbosity (int) β
motd_display (Optional[Dict[str, str]]) β
auto_tls (bool) β
single_process (bool) β
legacy (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)ο
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 (Union[str, bytes, PurePath]) β 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) β 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 (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 /content_type (Optional[bool]) β user defined content type for header
apply (bool) β
resource_type (Optional[str]) β
- 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 (Union[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 (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
name (Optional[str]) β 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 (Optional[Union[int, str, float]]) β
apply (bool) β
error_format (Optional[str]) β
- 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 (Union[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 (Union[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 (Optional[AsyncioServer]) β
- 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) β