Warning

These documents are OUTDATED as of 2023-12-31.

Please refer to the latest version of the documentation at sanic.dev.

Sanic Server

sanic.http

class sanic.http.Http(protocol)

Bases: Stream

β€œInternal helper for managing the HTTP/1.1 request/response cycle.

Raises:

BadRequest: If the request body is malformed. Exception: If the request is malformed. ExpectationFailed: If the request is malformed. PayloadTooLarge: If the request body exceeds the size limit. RuntimeError: If the response status is invalid. ServerError: If the handler does not produce a response. ServerError: If the response is bigger than the content-length.

create_empty_request()

Create an empty request object for error handling use.

Current error handling code needs a request object that won’t exist if an error occurred during before a request was received. Create a bogus response for error handling use.

Return type:

None

async error_response(exception)

Handle response when exception encountered

Parameters:

exception (Exception) –

Return type:

None

head_response_ignored(data, end_stream)

HEAD response: body data silently ignored.

Parameters:
  • data (bytes) –

  • end_stream (bool) –

Return type:

None

async http1()

HTTP 1.1 connection handler

async http1_request_header()

Receive and parse request header into self.request.

async http1_response_chunked(data, end_stream)

Format a part of response body in chunked encoding.

Parameters:
  • data (bytes) –

  • end_stream (bool) –

Return type:

None

async http1_response_header(data, end_stream)

Format response header and send it.

Parameters:
  • data (bytes) –

  • end_stream (bool) –

Return type:

None

async http1_response_normal(data, end_stream)

Format / keep track of non-chunked response.

Parameters:
  • data (bytes) –

  • end_stream (bool) –

Return type:

None

init_for_request()

Init/reset all per-request variables.

log_response()

Helper method provided to enable the logging of responses in case if the HttpProtocol.access_log is enabled.

Return type:

None

async read()

Read some bytes of request body.

Return type:

bytes | None

respond(response)

Initiate new streaming response.

Nothing is sent until the first send() call on the returned object, and calling this function multiple times will just alter the response to be given.

Parameters:

response (BaseHTTPResponse) –

Return type:

BaseHTTPResponse

class sanic.http.Http3(protocol, transmit)

Bases: object

Internal helper for managing the HTTP/3 request/response cycle

Parameters:
  • protocol (Http3Protocol) –

  • transmit (Callable[[], None]) –

enum sanic.http.Stage(value)

Bases: Enum

Enum for representing the stage of the request/response cycle

IDLE Waiting for request
REQUEST Request headers being received
HANDLER Headers done, handler running
RESPONSE Response headers sent, body in progress
FAILED Unrecoverable state (error while sending response)

Valid values are as follows:

IDLE = <Stage.IDLE: 0>
REQUEST = <Stage.REQUEST: 1>
HANDLER = <Stage.HANDLER: 3>
RESPONSE = <Stage.RESPONSE: 4>
FAILED = <Stage.FAILED: 100>

sanic.server

class sanic.server.AsyncioServer(app, loop, serve_coro, connections)

Bases: object

Wraps an asyncio server with functionality that might be useful to a user who needs to manage the server lifecycle manually.

Parameters:

app (Sanic) –

after_start()

Trigger β€œafter_server_start” events

after_stop()

Trigger β€œafter_server_stop” events

before_start()

Trigger β€œbefore_server_start” events

before_stop()

Trigger β€œbefore_server_stop” events

close()

Close the server

is_serving()

Returns True if the server is running, False otherwise

Return type:

bool

serve_forever()

Serve requests until the server is stopped

start_serving()

Start serving requests

startup()

Trigger β€œstartup” operations on the app

wait_closed()

Wait until the server is closed

class sanic.server.ConnInfo(transport, unix=None)

Bases: object

Local and remote addresses and SSL status info.

Parameters:

transport (TransportProtocol) –

class sanic.server.HttpProtocol(*, loop, app, signal=None, connections=None, state=None, unix=None, **kwargs)

Bases: HttpProtocolMixin, SanicProtocol

This class provides implements the HTTP 1.1 protocol on top of our Sanic Server transport

Parameters:

app (Sanic) –

HTTP_CLASS

alias of Http

check_timeouts()

Runs itself periodically to enforce any expired timeouts.

close(timeout=None)

Requires to prevent checking timeouts for closed connections

Parameters:

timeout (float | None) –

close_if_idle()

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

Returns:

boolean - True if closed, false if staying open

Return type:

bool

connection_made(transport)

HTTP-protocol-specific new connection handler

async connection_task()

Run a HTTP connection.

Timeouts and some additional error handling occur here, while most of everything else happens in class Http or in code called from there.

data_received(data)

Called when some data is received.

The argument is a bytes object.

Parameters:

data (bytes) –

async send(data)

Writes HTTP data with backpressure control.

sanic.server.serve(host, port, app, ssl=None, sock=None, unix=None, reuse_port=False, loop=None, protocol=<class 'sanic.server.protocols.http_protocol.HttpProtocol'>, backlog=100, register_sys_signals=True, run_multiple=False, run_async=False, connections=None, signal=<sanic.models.server_types.Signal object>, state=None, asyncio_server_kwargs=None, version=HTTP.VERSION_1)

Start asynchronous HTTP Server on an individual process.

Parameters:
  • host – Address to host on

  • port – Port to host on

  • 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

  • ssl (Optional[SSLContext]) – SSLContext

  • sock (Optional[socket.socket]) – Socket for the server to accept connections from

  • unix (Optional[str]) – Unix socket to listen on instead of TCP port

  • reuse_port (bool) – True for multiple workers

  • loop – asyncio compatible event loop

  • run_async (bool) – bool: Do not create a new event loop for the server, and return an AsyncServer object rather than running it

  • asyncio_server_kwargs – key-value args for asyncio/uvloop create_server method

  • app (Sanic) –

  • protocol (Type[asyncio.Protocol]) –

  • backlog (int) –

  • register_sys_signals (bool) –

  • run_multiple (bool) –

Returns:

Nothing

Args:

host (str): Address to host on port (int): Port to host on app (Sanic): Sanic app instance ssl (Optional[SSLContext], optional): SSLContext. Defaults to None. sock (Optional[socket.socket], optional): Socket for the server to

accept connections from. Defaults to None.

unix (Optional[str], optional): Unix socket to listen on instead of

TCP port. Defaults to None.

reuse_port (bool, optional): True for multiple workers. Defaults

to False.

loop: asyncio compatible event loop. Defaults

to None.

protocol (Type[asyncio.Protocol], optional): Protocol to use. Defaults

to HttpProtocol.

backlog (int, optional): The maximum number of queued connections

passed to socket.listen(). Defaults to 100.

register_sys_signals (bool, optional): Register SIGINT and SIGTERM.

Defaults to True.

run_multiple (bool, optional): Run multiple workers. Defaults

to False.

run_async (bool, optional): Return an AsyncServer object.

Defaults to False.

connections: Connections. Defaults to None. signal (Signal, optional): Signal. Defaults to Signal(). state: State. Defaults to None. asyncio_server_kwargs (Optional[Dict[str, Union[int, float]]], optional):

key-value args for asyncio/uvloop create_server method. Defaults to None.

version (str, optional): HTTP version. Defaults to HTTP.VERSION_1.

Raises:

ServerError: Cannot run HTTP/3 server without aioquic installed.

Returns:

AsyncioServer: AsyncioServer object if run_async is True.

sanic.server.try_use_uvloop()

Use uvloop instead of the default asyncio loop.

Return type:

None