API Reference

Submodules

sanic.app module

class sanic.app.Sanic(name=None, router=None, error_handler=None, load_env=True, request_class=None, strict_slashes=False, log_config=None, configure_logging=True)

Bases: object

add_route(handler, uri, methods=frozenset({'GET'}), host=None, strict_slashes=None, version=None, name=None, stream=False)

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

Parameters:
  • handler – function or class instance
  • uri – path of the URL
  • methods – list or tuple of methods allowed, these are overridden if using a HTTPMethodView
  • host
  • strict_slashes
  • version
  • name – user defined route name for url_for
  • stream – boolean specifying if the handler is a stream handler
Returns:

function or class instance

add_task(task)

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.

Parameters:task – future, couroutine or awaitable
add_websocket_route(handler, uri, host=None, strict_slashes=None, subprotocols=None, name=None)

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

blueprint(blueprint, **options)

Register a blueprint on the application.

Parameters:
  • blueprint – Blueprint object or (list, tuple) thereof
  • options – option dictionary with blueprint defaults
Returns:

Nothing

converted_response_type(response)
coroutine create_server(host=None, port=None, debug=False, ssl=None, sock=None, protocol=None, backlog=100, stop_event=None, access_log=True)

Asynchronous version of run.

NOTE: This does not support multiprocessing and is not the preferred
way to run a Sanic application.
delete(uri, host=None, strict_slashes=None, version=None, name=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)

Decorate a function to be registered as a handler for exceptions

Parameters:exceptions – exceptions
Returns:decorated function
get(uri, host=None, strict_slashes=None, version=None, name=None)
coroutine handle_request(request, write_callback, stream_callback)

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 – HTTP Request object
  • write_callback – Synchronous response function to be called with the response as the only argument
  • stream_callback – Coroutine that handles streaming a StreamingHTTPResponse if produced by the handler.
Returns:

Nothing

head(uri, host=None, strict_slashes=None, version=None, name=None)
listener(event)

Create a listener from a decorated function.

Parameters:event – event to listen to
loop

Synonymous with asyncio.get_event_loop().

Only supported when using the app.run method.

middleware(middleware_or_request)

Decorate and register middleware to be called before a request. Can either be called as @app.middleware or @app.middleware(‘request’)

options(uri, host=None, strict_slashes=None, version=None, name=None)
patch(uri, host=None, strict_slashes=None, stream=False, version=None, name=None)
post(uri, host=None, strict_slashes=None, stream=False, version=None, name=None)
put(uri, host=None, strict_slashes=None, stream=False, version=None, name=None)
register_blueprint(*args, **kwargs)
register_listener(listener, event)

Register the listener for a given event.

Args:
listener: callable i.e. setup_db(app, loop) event: when to register listener i.e. ‘before_server_start’

Returns: listener

register_middleware(middleware, attach_to='request')
remove_route(uri, clean_cache=True, host=None)
route(uri, methods=frozenset({'GET'}), host=None, strict_slashes=None, stream=False, version=None, name=None)

Decorate a function to be registered as a route

Parameters:
  • uri – path of the URL
  • methods – list or tuple of methods allowed
  • host
  • strict_slashes
  • stream
  • version
  • name – user defined route name for url_for
Returns:

decorated function

run(host=None, port=None, debug=False, ssl=None, sock=None, workers=1, protocol=None, backlog=100, stop_event=None, register_sys_signals=True, access_log=True, **kwargs)
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)

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

stop()

This kills the Sanic

test_client
coroutine trigger_events(events, loop)

Trigger events (functions or async) :param events: one or more sync or async functions to execute :param loop: event loop

url_for(view_name: str, **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.

Parameters:
  • view_name – 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, name=None)

Decorate a function to be registered as a websocket route :param uri: path of the URL :param subprotocols: optional list of str with supported subprotocols :param host: :return: decorated function

sanic.blueprints module

class sanic.blueprints.Blueprint(name, url_prefix=None, host=None, version=None, strict_slashes=False)

Bases: object

add_route(handler, uri, methods=frozenset({'GET'}), host=None, strict_slashes=None, version=None, name=None)

Create a blueprint route from a function.

Parameters:
  • handler – function for handling uri requests. Accepts function, or class instance with a view_class method.
  • uri – endpoint at which the route will be accessible.
  • methods – list of acceptable HTTP methods.
  • host
  • strict_slashes
  • version
  • name – user defined route name for url_for
Returns:

function or class instance

add_websocket_route(handler, uri, host=None, version=None, name=None)

Create a blueprint websocket route from a function.

Parameters:
  • handler – function for handling uri requests. Accepts function, or class instance with a view_class method.
  • uri – endpoint at which the route will be accessible.
Returns:

function or class instance

delete(uri, host=None, strict_slashes=None, version=None, name=None)
exception(*args, **kwargs)

Create a blueprint exception from a decorated function.

get(uri, host=None, strict_slashes=None, version=None, name=None)
static group(*blueprints, url_prefix='')

Create a list of blueprints, optionally grouping them under a general URL prefix.

Parameters:
  • blueprints – blueprints to be registered as a group
  • url_prefix – URL route to be prepended to all sub-prefixes
head(uri, host=None, strict_slashes=None, version=None, name=None)
listener(event)

Create a listener from a decorated function.

Parameters:event – Event to listen to.
middleware(*args, **kwargs)

Create a blueprint middleware from a decorated function.

options(uri, host=None, strict_slashes=None, version=None, name=None)
patch(uri, host=None, strict_slashes=None, stream=False, version=None, name=None)
post(uri, host=None, strict_slashes=None, stream=False, version=None, name=None)
put(uri, host=None, strict_slashes=None, stream=False, version=None, name=None)
register(app, options)

Register the blueprint to the sanic app.

route(uri, methods=frozenset({'GET'}), host=None, strict_slashes=None, stream=False, version=None, name=None)

Create a blueprint route from a decorated function.

Parameters:
  • uri – endpoint at which the route will be accessible.
  • methods – list of acceptable HTTP methods.
static(uri, file_or_directory, *args, **kwargs)

Create a blueprint static route from a decorated function.

Parameters:
  • uri – endpoint at which the route will be accessible.
  • file_or_directory – Static asset.
websocket(uri, host=None, strict_slashes=None, version=None, name=None)

Create a blueprint websocket route from a decorated function.

Parameters:uri – endpoint at which the route will be accessible.
class sanic.blueprints.FutureException(handler, args, kwargs)

Bases: tuple

args

Alias for field number 1

handler

Alias for field number 0

kwargs

Alias for field number 2

class sanic.blueprints.FutureListener(handler, uri, methods, host)

Bases: tuple

handler

Alias for field number 0

host

Alias for field number 3

methods

Alias for field number 2

uri

Alias for field number 1

class sanic.blueprints.FutureMiddleware(middleware, args, kwargs)

Bases: tuple

args

Alias for field number 1

kwargs

Alias for field number 2

middleware

Alias for field number 0

class sanic.blueprints.FutureRoute(handler, uri, methods, host, strict_slashes, stream, version, name)

Bases: tuple

handler

Alias for field number 0

host

Alias for field number 3

methods

Alias for field number 2

name

Alias for field number 7

stream

Alias for field number 5

strict_slashes

Alias for field number 4

uri

Alias for field number 1

version

Alias for field number 6

class sanic.blueprints.FutureStatic(uri, file_or_directory, args, kwargs)

Bases: tuple

args

Alias for field number 2

file_or_directory

Alias for field number 1

kwargs

Alias for field number 3

uri

Alias for field number 0

sanic.config module

class sanic.config.Config(defaults=None, load_env=True, keep_alive=True)

Bases: dict

from_envvar(variable_name)

Load a configuration from an environment variable pointing to a configuration file.

Parameters:variable_name – name of the environment variable
Returns:bool. True if able to load config, False otherwise.
from_object(obj)

Update the values from the given object. Objects are usually either modules or classes.

Just the uppercase variables in that object are stored in the config. Example usage:

from yourapplication import default_config
app.config.from_object(default_config)

You should not use this function to load the actual configuration but rather configuration defaults. The actual config should be loaded with from_pyfile() and ideally from a location not within the package because the package might be installed system wide.

Parameters:obj – an object holding the configuration
from_pyfile(filename)

Update the values in the config from a Python file. Only the uppercase variables in that module are stored in the config.

Parameters:filename – an absolute path to the config file
load_environment_vars(prefix='SANIC_')

Looks for prefixed environment variables and applies them to the configuration if present.

sanic.constants module

sanic.cookies module

class sanic.cookies.Cookie(key, value)

Bases: dict

A stripped down version of Morsel from SimpleCookie #gottagofast

encode(encoding)
class sanic.cookies.CookieJar(headers)

Bases: dict

CookieJar dynamically writes headers as cookies are added and removed It gets around the limitation of one header per name by using the MultiHeader class to provide a unique key that encodes to Set-Cookie.

sanic.exceptions module

exception sanic.exceptions.ContentRangeError(message, content_range)

Bases: sanic.exceptions.SanicException

status_code = 416
exception sanic.exceptions.FileNotFound(message, path, relative_url)

Bases: sanic.exceptions.NotFound

exception sanic.exceptions.Forbidden(message, status_code=None)

Bases: sanic.exceptions.SanicException

status_code = 403
exception sanic.exceptions.HeaderNotFound(message, status_code=None)

Bases: sanic.exceptions.InvalidUsage

exception sanic.exceptions.InvalidRangeType(message, content_range)

Bases: sanic.exceptions.ContentRangeError

exception sanic.exceptions.InvalidUsage(message, status_code=None)

Bases: sanic.exceptions.SanicException

status_code = 400
exception sanic.exceptions.MethodNotSupported(message, method, allowed_methods)

Bases: sanic.exceptions.SanicException

status_code = 405
exception sanic.exceptions.NotFound(message, status_code=None)

Bases: sanic.exceptions.SanicException

status_code = 404
exception sanic.exceptions.PayloadTooLarge(message, status_code=None)

Bases: sanic.exceptions.SanicException

status_code = 413
exception sanic.exceptions.PyFileError(file)

Bases: Exception

exception sanic.exceptions.RequestTimeout(message, status_code=None)

Bases: sanic.exceptions.SanicException

The Web server (running the Web site) thinks that there has been too long an interval of time between 1) the establishment of an IP connection (socket) between the client and the server and 2) the receipt of any data on that socket, so the server has dropped the connection. The socket connection has actually been lost - the Web server has ‘timed out’ on that particular socket connection.

status_code = 408
exception sanic.exceptions.SanicException(message, status_code=None)

Bases: Exception

exception sanic.exceptions.ServerError(message, status_code=None)

Bases: sanic.exceptions.SanicException

status_code = 500
exception sanic.exceptions.ServiceUnavailable(message, status_code=None)

Bases: sanic.exceptions.SanicException

The server is currently unavailable (because it is overloaded or down for maintenance). Generally, this is a temporary state.

status_code = 503
exception sanic.exceptions.URLBuildError(message, status_code=None)

Bases: sanic.exceptions.ServerError

exception sanic.exceptions.Unauthorized(message, status_code=None, scheme=None, **kwargs)

Bases: sanic.exceptions.SanicException

Unauthorized exception (401 HTTP status code).

Parameters:
  • message – Message describing the exception.
  • status_code – HTTP Status code.
  • scheme – Name of the authentication scheme to be used.

When present, kwargs is used to complete the WWW-Authentication header.

Examples:

# With a Basic auth-scheme, realm MUST be present:
raise Unauthorized("Auth required.",
                   scheme="Basic",
                   realm="Restricted Area")

# With a Digest auth-scheme, things are a bit more complicated:
raise Unauthorized("Auth required.",
                   scheme="Digest",
                   realm="Restricted Area",
                   qop="auth, auth-int",
                   algorithm="MD5",
                   nonce="abcdef",
                   opaque="zyxwvu")

# With a Bearer auth-scheme, realm is optional so you can write:
raise Unauthorized("Auth required.", scheme="Bearer")

# or, if you want to specify the realm:
raise Unauthorized("Auth required.",
                   scheme="Bearer",
                   realm="Restricted Area")
status_code = 401
sanic.exceptions.abort(status_code, message=None)

Raise an exception based on SanicException. Returns the HTTP response message appropriate for the given status code, unless provided.

Parameters:
  • status_code – The HTTP status code to return.
  • message – The HTTP response body. Defaults to the messages in response.py for the given status code.
sanic.exceptions.add_status_code(code)

Decorator used for adding exceptions to _sanic_exceptions.

sanic.handlers module

class sanic.handlers.ContentRangeHandler(request, stats)

Bases: object

Class responsible for parsing request header

end
headers
size
start
total
class sanic.handlers.ErrorHandler

Bases: object

add(exception, handler)
cached_handlers = None
default(request, exception)
handlers = None
log(message, level='error')

Deprecated, do not use.

lookup(exception)
response(request, exception)

Fetches and executes an exception handler and returns a response object

Parameters:
  • request – Request
  • exception – Exception to handle
Returns:

Response object

sanic.log module

sanic.request module

class sanic.request.File(type, body, name)

Bases: tuple

body

Alias for field number 1

name

Alias for field number 2

type

Alias for field number 0

class sanic.request.Request(url_bytes, headers, version, method, transport)

Bases: dict

Properties of an HTTP request such as URL, headers, etc.

app
args
body
body_finish()
body_init()
body_push(data)
content_type
cookies
files
form
headers
host
ip
json
load_json(loads=<built-in function loads>)
match_info

return matched info after resolving route

method
parsed_args
parsed_files
parsed_form
parsed_json
path
port
query_string
raw_args
raw_url
remote_addr

Attempt to return the original client ip based on X-Forwarded-For.

Returns:original client ip.
scheme
socket
stream
token

Attempt to return the auth header token.

Returns:token related to request
transport
uri_template
url
version
class sanic.request.RequestParameters

Bases: dict

Hosts a dict with lists as values where get returns the first value of the list and getlist returns the whole shebang

get(name, default=None)

Return the first value, either the default or actual

getlist(name, default=None)

Return the entire list

sanic.request.parse_multipart_form(body, boundary)

Parse a request body and returns fields and files

Parameters:
  • body – bytes request body
  • boundary – bytes multipart boundary
Returns:

fields (RequestParameters), files (RequestParameters)

sanic.response module

class sanic.response.BaseHTTPResponse

Bases: object

cookies
class sanic.response.HTTPResponse(body=None, status=200, headers=None, content_type='text/plain', body_bytes=b'')

Bases: sanic.response.BaseHTTPResponse

body
content_type
cookies
headers
output(version='1.1', keep_alive=False, keep_alive_timeout=None)
status
class sanic.response.StreamingHTTPResponse(streaming_fn, status=200, headers=None, content_type='text/plain')

Bases: sanic.response.BaseHTTPResponse

content_type
get_headers(version='1.1', keep_alive=False, keep_alive_timeout=None)
headers
protocol
status
coroutine stream(version='1.1', keep_alive=False, keep_alive_timeout=None)

Streams headers, runs the streaming_fn callback that writes content to the response body, then finalizes the response body.

streaming_fn
coroutine write(data)

Writes a chunk of data to the streaming response.

Parameters:data – bytes-ish data to be written.
coroutine sanic.response.file(location, status=200, mime_type=None, headers=None, filename=None, _range=None)

Return a response object with file data.

Parameters:
  • location – Location of file on system.
  • mime_type – Specific mime_type.
  • headers – Custom Headers.
  • filename – Override filename.
  • _range
coroutine sanic.response.file_stream(location, status=200, chunk_size=4096, mime_type=None, headers=None, filename=None, _range=None)

Return a streaming response object with file data.

Parameters:
  • location – Location of file on system.
  • chunk_size – The size of each chunk in the stream (in bytes)
  • mime_type – Specific mime_type.
  • headers – Custom Headers.
  • filename – Override filename.
  • _range
sanic.response.html(body, status=200, headers=None)

Returns response object with body in html format.

Parameters:
  • body – Response data to be encoded.
  • status – Response code.
  • headers – Custom Headers.
sanic.response.json(body, status=200, headers=None, content_type='application/json', dumps=<built-in function dumps>, **kwargs)

Returns response object with body in json format.

Parameters:
  • body – Response data to be serialized.
  • status – Response code.
  • headers – Custom Headers.
  • kwargs – Remaining arguments that are passed to the json encoder.
sanic.response.raw(body, status=200, headers=None, content_type='application/octet-stream')

Returns response object without encoding the body.

Parameters:
  • body – Response data.
  • status – Response code.
  • headers – Custom Headers.
  • content_type – the content type (string) of the response.
sanic.response.redirect(to, headers=None, status=302, content_type='text/html; charset=utf-8')

Abort execution and cause a 302 redirect (by default).

Parameters:
  • to – path or fully qualified URL to redirect to
  • headers – optional dict of headers to include in the new request
  • status – status code (int) of the new request, defaults to 302
  • content_type – the content type (string) of the response
Returns:

the redirecting Response

sanic.response.stream(streaming_fn, status=200, headers=None, content_type='text/plain; charset=utf-8')

Accepts an coroutine streaming_fn which can be used to write chunks to a streaming response. Returns a StreamingHTTPResponse.

Example usage:

@app.route("/")
async def index(request):
    async def streaming_fn(response):
        await response.write('foo')
        await response.write('bar')

    return stream(streaming_fn, content_type='text/plain')
Parameters:
  • streaming_fn – A coroutine accepts a response and writes content to that response.
  • mime_type – Specific mime_type.
  • headers – Custom Headers.
sanic.response.text(body, status=200, headers=None, content_type='text/plain; charset=utf-8')

Returns response object with body in text format.

Parameters:
  • body – Response data to be encoded.
  • status – Response code.
  • headers – Custom Headers.
  • content_type – the content type (string) of the response

sanic.router module

class sanic.router.Parameter(name, cast)

Bases: tuple

cast

Alias for field number 1

name

Alias for field number 0

exception sanic.router.ParameterNameConflicts

Bases: Exception

class sanic.router.Route(handler, methods, pattern, parameters, name, uri)

Bases: tuple

handler

Alias for field number 0

methods

Alias for field number 1

name

Alias for field number 4

parameters

Alias for field number 3

pattern

Alias for field number 2

uri

Alias for field number 5

exception sanic.router.RouteDoesNotExist

Bases: Exception

exception sanic.router.RouteExists

Bases: Exception

class sanic.router.Router

Bases: object

Router supports basic routing with parameters and method checks

Usage:

@sanic.route('/my/url/<my_param>', methods=['GET', 'POST', ...])
def my_route(request, my_param):
    do stuff...

or

@sanic.route('/my/url/<my_param:my_type>', methods['GET', 'POST', ...])
def my_route_with_type(request, my_param: my_type):
    do stuff...

Parameters will be passed as keyword arguments to the request handling function. Provided parameters can also have a type by appending :type to the <parameter>. Given parameter must be able to be type-casted to this. If no type is provided, a string is expected. A regular expression can also be passed in as the type. The argument given to the function will always be a string, independent of the type.

add(uri, methods, handler, host=None, strict_slashes=False, version=None, name=None)

Add a handler to the route list

Parameters:
  • uri – path to match
  • methods – sequence of accepted method names. If none are provided, any method is allowed
  • handler – request handler function. When executed, it should provide a response object.
  • strict_slashes – strict to trailing slash
  • version – current version of the route or blueprint. See docs for further details.
Returns:

Nothing

static check_dynamic_route_exists(pattern, routes_to_check, parameters)
find_route_by_view_name

Find a route in the router based on the specified view name.

Parameters:
  • view_name – string of view name to search by
  • kwargs – additional params, usually for static files
Returns:

tuple containing (uri, Route)

get(request)

Get a request handler based on the URL of the request, or raises an error

Parameters:request – Request object
Returns:handler, arguments, keyword arguments
get_supported_methods(url)

Get a list of supported methods for a url and optional host.

Parameters:url – URL string (including host)
Returns:frozenset of supported methods
is_stream_handler(request)

Handler for request is stream or not. :param request: Request object :return: bool

parameter_pattern = re.compile('<(.+?)>')
classmethod parse_parameter_string(parameter_string)

Parse a parameter string into its constituent name, type, and pattern

For example:

parse_parameter_string('<param_one:[A-z]>')` ->
    ('param_one', str, '[A-z]')
Parameters:parameter_string – String to parse
Returns:tuple containing (parameter_name, parameter_type, parameter_pattern)
remove(uri, clean_cache=True, host=None)
routes_always_check = None
routes_dynamic = None
routes_static = None
sanic.router.url_hash(url)

sanic.server module

class sanic.server.HttpProtocol(*, loop, request_handler, error_handler, signal=<sanic.server.Signal object>, connections={}, request_timeout=60, response_timeout=60, keep_alive_timeout=5, request_max_size=None, request_class=None, access_log=True, keep_alive=True, is_request_stream=False, router=None, state=None, debug=False, **kwargs)

Bases: asyncio.protocols.Protocol

access_log
bail_out(message, from_error=False)
cleanup()

This is called when KeepAlive feature is used, it resets the connection in order for it to be able to handle receiving another request on the same connection.

close()

Force close the connection.

close_if_idle()

Close the connection if a request is not being sent or received

Returns:boolean - True if closed, false if staying open
connection_lost(exc)

Called when the connection is lost or closed.

The argument is an exception object or None (the latter meaning a regular EOF is received or the connection was aborted or closed).

connection_made(transport)

Called when a connection is made.

The argument is the transport representing the pipe connection. To receive data, wait for data_received() calls. When the connection is closed, connection_lost() is called.

connections
data_received(data)

Called when some data is received.

The argument is a bytes object.

coroutine drain()
execute_request_handler()
headers
is_request_stream
keep_alive
keep_alive_timeout
keep_alive_timeout_callback()
log_response(response)
loop
on_body(body)
on_header(name, value)
on_headers_complete()
on_message_complete()
on_url(url)
parser
pause_writing()

Called when the transport’s buffer goes over the high-water mark.

Pause and resume calls are paired – pause_writing() is called once when the buffer goes strictly over the high-water mark (even if subsequent writes increases the buffer size even more), and eventually resume_writing() is called once when the buffer size reaches the low-water mark.

Note that if the buffer size equals the high-water mark, pause_writing() is not called – it must go strictly over. Conversely, resume_writing() is called when the buffer size is equal or lower than the low-water mark. These end conditions are important to ensure that things go as expected when either mark is zero.

NOTE: This is the only Protocol callback that is not called through EventLoop.call_soon() – if it were, it would have no effect when it’s most needed (when the app keeps writing without yielding until pause_writing() is called).

push_data(data)
request
request_class
request_handler
request_max_size
request_timeout
request_timeout_callback()
response_timeout
response_timeout_callback()
resume_writing()

Called when the transport’s buffer drains below the low-water mark.

See pause_writing() for details.

router
signal
coroutine stream_response(response)

Streams a response to the client asynchronously. Attaches the transport to the response so the response consumer can write to the response as needed.

transport
url
write_error(exception)
write_response(response)

Writes response content synchronously to the transport.

class sanic.server.Signal

Bases: object

stopped = False
sanic.server.serve(host, port, request_handler, error_handler, before_start=None, after_start=None, before_stop=None, after_stop=None, debug=False, request_timeout=60, response_timeout=60, keep_alive_timeout=5, ssl=None, sock=None, request_max_size=None, reuse_port=False, loop=None, protocol=<class 'sanic.server.HttpProtocol'>, backlog=100, register_sys_signals=True, run_multiple=False, run_async=False, connections=None, signal=<sanic.server.Signal object>, request_class=None, access_log=True, keep_alive=True, is_request_stream=False, router=None, websocket_max_size=None, websocket_max_queue=None, websocket_read_limit=65536, websocket_write_limit=65536, state=None, graceful_shutdown_timeout=15.0)

Start asynchronous HTTP Server on an individual process.

Parameters:
  • host – Address to host on
  • port – Port to host on
  • request_handler – Sanic request handler with middleware
  • error_handler – Sanic error handler with middleware
  • before_start – function to be executed before the server starts listening. Takes arguments app instance and loop
  • after_start – function to be executed after the server starts listening. Takes arguments app instance and loop
  • before_stop – function to be executed when a stop signal is received before it is respected. Takes arguments app instance and loop
  • after_stop – function to be executed when a stop signal is received after it is respected. Takes arguments app instance and loop
  • debug – enables debug output (slows server)
  • request_timeout – time in seconds
  • response_timeout – time in seconds
  • keep_alive_timeout – time in seconds
  • ssl – SSLContext
  • sock – Socket for the server to accept connections from
  • request_max_size – size in bytes, None for no limit
  • reuse_portTrue for multiple workers
  • loop – asyncio compatible event loop
  • protocol – subclass of asyncio protocol class
  • request_class – Request class to use
  • access_log – disable/enable access log
  • websocket_max_size – enforces the maximum size for incoming messages in bytes.
  • websocket_max_queue – sets the maximum length of the queue that holds incoming messages.
  • websocket_read_limit – sets the high-water limit of the buffer for incoming bytes, the low-water limit is half the high-water limit.
  • websocket_write_limit – sets the high-water limit of the buffer for outgoing bytes, the low-water limit is a quarter of the high-water limit.
  • is_request_stream – disable/enable Request.stream
  • router – Router object
  • graceful_shutdown_timeout – How long take to Force close non-idle connection
Returns:

Nothing

sanic.server.serve_multiple(server_settings, workers)

Start multiple server processes simultaneously. Stop on interrupt and terminate signals, and drain connections when complete.

Parameters:
  • server_settings – kw arguments to be passed to the serve function
  • workers – number of workers to launch
  • stop_event – if provided, is used as a stop signal
Returns:

sanic.server.trigger_events(events, loop)

Trigger event callbacks (functions or async)

Parameters:
  • events – one or more sync or async functions to execute
  • loop – event loop
sanic.server.update_current_time(loop)

Cache the current time, since it is needed at the end of every keep-alive request to update the request timeout time

Parameters:loop
Returns:

sanic.static module

sanic.static.register(app, uri, file_or_directory, pattern, use_modified_since, use_content_range, stream_large_files, name='static', host=None, strict_slashes=None, content_type=None)

Register a static directory handler with Sanic by adding a route to the router and registering a handler.

Parameters:
  • app – Sanic
  • file_or_directory – File or directory path to serve from
  • uri – URL to serve from
  • pattern – regular expression used to match files in the URL
  • use_modified_since – If true, send file modified time, and return not modified if the browser’s matches the server’s
  • use_content_range – If true, process header for range requests and sends the file part that is requested
  • stream_large_files – If true, use the file_stream() handler rather than the file() handler to send the file If this is an integer, this represents the threshold size to switch to file_stream()
  • name – user defined name used for url_for
  • content_type – user defined content type for header

sanic.testing module

class sanic.testing.SanicTestClient(app, port=42101)

Bases: object

delete(*args, **kwargs)
get(*args, **kwargs)
head(*args, **kwargs)
options(*args, **kwargs)
patch(*args, **kwargs)
post(*args, **kwargs)
put(*args, **kwargs)

sanic.views module

class sanic.views.CompositionView

Bases: object

Simple method-function mapped view for the sanic. You can add handler functions to methods (get, post, put, patch, delete) for every HTTP method you want to support.

For example:
view = CompositionView() view.add([‘GET’], lambda request: text(‘I am get method’)) view.add([‘POST’, ‘PUT’], lambda request: text(‘I am post/put method’))

etc.

If someone tries to use a non-implemented method, there will be a 405 response.

add(methods, handler, stream=False)
class sanic.views.HTTPMethodView

Bases: object

Simple class based implementation of view for the sanic. You should implement methods (get, post, put, patch, delete) for the class to every HTTP method you want to support.

For example:

class DummyView(HTTPMethodView):
    def get(self, request, *args, **kwargs):
        return text('I am get method')
    def put(self, request, *args, **kwargs):
        return text('I am put method')

etc.

If someone tries to use a non-implemented method, there will be a 405 response.

If you need any url params just mention them in method definition:

class DummyView(HTTPMethodView):
    def get(self, request, my_param_here, *args, **kwargs):
        return text('I am get method with %s' % my_param_here)
To add the view into the routing you could use
  1. app.add_route(DummyView.as_view(), ‘/’)
  2. app.route(‘/’)(DummyView.as_view())

To add any decorator you could set it into decorators variable

classmethod as_view(*class_args, **class_kwargs)

Return view function for use with the routing system, that dispatches request to appropriate handler method.

decorators = []
dispatch_request(request, *args, **kwargs)
sanic.views.stream(func)

sanic.websocket module

class sanic.websocket.WebSocketProtocol(*args, websocket_timeout=10, websocket_max_size=None, websocket_max_queue=None, websocket_read_limit=65536, websocket_write_limit=65536, **kwargs)

Bases: sanic.server.HttpProtocol

connection_lost(exc)

Called when the connection is lost or closed.

The argument is an exception object or None (the latter meaning a regular EOF is received or the connection was aborted or closed).

data_received(data)

Called when some data is received.

The argument is a bytes object.

keep_alive_timeout_callback()
request_timeout_callback()
response_timeout_callback()
coroutine websocket_handshake(request, subprotocols=None)
write_response(response)

Writes response content synchronously to the transport.

sanic.worker module

Module contents

class sanic.Sanic(name=None, router=None, error_handler=None, load_env=True, request_class=None, strict_slashes=False, log_config=None, configure_logging=True)

Bases: object

add_route(handler, uri, methods=frozenset({'GET'}), host=None, strict_slashes=None, version=None, name=None, stream=False)

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

Parameters:
  • handler – function or class instance
  • uri – path of the URL
  • methods – list or tuple of methods allowed, these are overridden if using a HTTPMethodView
  • host
  • strict_slashes
  • version
  • name – user defined route name for url_for
  • stream – boolean specifying if the handler is a stream handler
Returns:

function or class instance

add_task(task)

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.

Parameters:task – future, couroutine or awaitable
add_websocket_route(handler, uri, host=None, strict_slashes=None, subprotocols=None, name=None)

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

blueprint(blueprint, **options)

Register a blueprint on the application.

Parameters:
  • blueprint – Blueprint object or (list, tuple) thereof
  • options – option dictionary with blueprint defaults
Returns:

Nothing

converted_response_type(response)
coroutine create_server(host=None, port=None, debug=False, ssl=None, sock=None, protocol=None, backlog=100, stop_event=None, access_log=True)

Asynchronous version of run.

NOTE: This does not support multiprocessing and is not the preferred
way to run a Sanic application.
delete(uri, host=None, strict_slashes=None, version=None, name=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)

Decorate a function to be registered as a handler for exceptions

Parameters:exceptions – exceptions
Returns:decorated function
get(uri, host=None, strict_slashes=None, version=None, name=None)
coroutine handle_request(request, write_callback, stream_callback)

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 – HTTP Request object
  • write_callback – Synchronous response function to be called with the response as the only argument
  • stream_callback – Coroutine that handles streaming a StreamingHTTPResponse if produced by the handler.
Returns:

Nothing

head(uri, host=None, strict_slashes=None, version=None, name=None)
listener(event)

Create a listener from a decorated function.

Parameters:event – event to listen to
loop

Synonymous with asyncio.get_event_loop().

Only supported when using the app.run method.

middleware(middleware_or_request)

Decorate and register middleware to be called before a request. Can either be called as @app.middleware or @app.middleware(‘request’)

options(uri, host=None, strict_slashes=None, version=None, name=None)
patch(uri, host=None, strict_slashes=None, stream=False, version=None, name=None)
post(uri, host=None, strict_slashes=None, stream=False, version=None, name=None)
put(uri, host=None, strict_slashes=None, stream=False, version=None, name=None)
register_blueprint(*args, **kwargs)
register_listener(listener, event)

Register the listener for a given event.

Args:
listener: callable i.e. setup_db(app, loop) event: when to register listener i.e. ‘before_server_start’

Returns: listener

register_middleware(middleware, attach_to='request')
remove_route(uri, clean_cache=True, host=None)
route(uri, methods=frozenset({'GET'}), host=None, strict_slashes=None, stream=False, version=None, name=None)

Decorate a function to be registered as a route

Parameters:
  • uri – path of the URL
  • methods – list or tuple of methods allowed
  • host
  • strict_slashes
  • stream
  • version
  • name – user defined route name for url_for
Returns:

decorated function

run(host=None, port=None, debug=False, ssl=None, sock=None, workers=1, protocol=None, backlog=100, stop_event=None, register_sys_signals=True, access_log=True, **kwargs)
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)

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

stop()

This kills the Sanic

test_client
coroutine trigger_events(events, loop)

Trigger events (functions or async) :param events: one or more sync or async functions to execute :param loop: event loop

url_for(view_name: str, **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.

Parameters:
  • view_name – 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, name=None)

Decorate a function to be registered as a websocket route :param uri: path of the URL :param subprotocols: optional list of str with supported subprotocols :param host: :return: decorated function

class sanic.Blueprint(name, url_prefix=None, host=None, version=None, strict_slashes=False)

Bases: object

add_route(handler, uri, methods=frozenset({'GET'}), host=None, strict_slashes=None, version=None, name=None)

Create a blueprint route from a function.

Parameters:
  • handler – function for handling uri requests. Accepts function, or class instance with a view_class method.
  • uri – endpoint at which the route will be accessible.
  • methods – list of acceptable HTTP methods.
  • host
  • strict_slashes
  • version
  • name – user defined route name for url_for
Returns:

function or class instance

add_websocket_route(handler, uri, host=None, version=None, name=None)

Create a blueprint websocket route from a function.

Parameters:
  • handler – function for handling uri requests. Accepts function, or class instance with a view_class method.
  • uri – endpoint at which the route will be accessible.
Returns:

function or class instance

delete(uri, host=None, strict_slashes=None, version=None, name=None)
exception(*args, **kwargs)

Create a blueprint exception from a decorated function.

get(uri, host=None, strict_slashes=None, version=None, name=None)
static group(*blueprints, url_prefix='')

Create a list of blueprints, optionally grouping them under a general URL prefix.

Parameters:
  • blueprints – blueprints to be registered as a group
  • url_prefix – URL route to be prepended to all sub-prefixes
head(uri, host=None, strict_slashes=None, version=None, name=None)
listener(event)

Create a listener from a decorated function.

Parameters:event – Event to listen to.
middleware(*args, **kwargs)

Create a blueprint middleware from a decorated function.

options(uri, host=None, strict_slashes=None, version=None, name=None)
patch(uri, host=None, strict_slashes=None, stream=False, version=None, name=None)
post(uri, host=None, strict_slashes=None, stream=False, version=None, name=None)
put(uri, host=None, strict_slashes=None, stream=False, version=None, name=None)
register(app, options)

Register the blueprint to the sanic app.

route(uri, methods=frozenset({'GET'}), host=None, strict_slashes=None, stream=False, version=None, name=None)

Create a blueprint route from a decorated function.

Parameters:
  • uri – endpoint at which the route will be accessible.
  • methods – list of acceptable HTTP methods.
static(uri, file_or_directory, *args, **kwargs)

Create a blueprint static route from a decorated function.

Parameters:
  • uri – endpoint at which the route will be accessible.
  • file_or_directory – Static asset.
websocket(uri, host=None, strict_slashes=None, version=None, name=None)

Create a blueprint websocket route from a decorated function.

Parameters:uri – endpoint at which the route will be accessible.