Sanic Server¶

sanic.http¶

class sanic.http.Http(protocol)¶

Bases: object

Internal helper for managing the HTTP request/response cycle

Raises
create_empty_request()¶

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_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

Optional[bytes]

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.Stage(value)¶

Bases: enum.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)

sanic.server¶

class sanic.server.AsyncioServer(loop, serve_coro, connections, after_start, before_stop, after_stop)¶

Bases: object

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

Parameters
  • after_start (Optional[Iterable[ListenerType]]) –

  • before_stop (Optional[Iterable[ListenerType]]) –

  • after_stop (Optional[Iterable[ListenerType]]) –

after_start()¶

Trigger “after_server_start” events

after_stop()¶

Trigger “after_server_stop” events

before_stop()¶

Trigger “before_server_stop” events

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: asyncio.protocols.Protocol

This class provides a basic HTTP implementation of the sanic framework.

Parameters

app (Sanic) –

check_timeouts()¶

Runs itself periodically to enforce any expired timeouts.

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

Return type

bool

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.

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) –

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).

async receive_more()¶

Wait until more data is received into the Server protocol’s buffer

resume_writing()¶

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

See pause_writing() for details.

async send(data)¶

Writes data with backpressure control.

sanic.server.bind_socket(host, port, *, backlog=100)¶

Create TCP server socket. :param host: IPv4, IPv6 or hostname may be specified :param port: TCP port number :param backlog: Maximum number of connections to queue :return: socket.socket object

Parameters
  • host (str) –

  • port (int) –

Return type

socket.socket

sanic.server.bind_unix_socket(path, *, mode=438, backlog=100)¶

Create unix socket. :param path: filesystem path :param backlog: Maximum number of connections to queue :return: socket.socket object

Parameters

path (str) –

Return type

socket.socket

sanic.server.remove_unix_socket(path)¶

Remove dead unix socket during server exit.

Parameters

path (Optional[str]) –

Return type

None

sanic.server.serve(host, port, app, before_start=None, after_start=None, before_stop=None, after_stop=None, ssl=None, sock=None, unix=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>, state=None, asyncio_server_kwargs=None)¶

Start asynchronous HTTP Server on an individual process.

Parameters
  • host – Address to host on

  • port – Port to host on

  • before_start (Optional[Iterable[Callable[[sanic.models.handler_types.Sanic, asyncio.events.AbstractEventLoop], Optional[Coroutine[Any, Any, None]]]]]) – function to be executed before the server starts listening. Takes arguments app instance and loop

  • after_start (Optional[Iterable[Callable[[sanic.models.handler_types.Sanic, asyncio.events.AbstractEventLoop], Optional[Coroutine[Any, Any, None]]]]]) – function to be executed after the server starts listening. Takes arguments app instance and loop

  • before_stop (Optional[Iterable[Callable[[sanic.models.handler_types.Sanic, asyncio.events.AbstractEventLoop], Optional[Coroutine[Any, Any, None]]]]]) – function to be executed when a stop signal is received before it is respected. Takes arguments app instance and loop

  • after_stop (Optional[Iterable[Callable[[sanic.models.handler_types.Sanic, asyncio.events.AbstractEventLoop], Optional[Coroutine[Any, Any, None]]]]]) – function to be executed when a stop signal is received after it is respected. Takes arguments app instance and loop

  • ssl (Optional[ssl.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

  • protocol (Type[asyncio.protocols.Protocol]) –

  • backlog (int) –

  • register_sys_signals (bool) –

  • run_multiple (bool) –

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 (Optional[Iterable[Callable[[...], Any]]]) – one or more sync or async functions to execute

  • loop – event loop

sanic.worker¶