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:
- 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 requestREQUEST
Request headers being receivedHANDLER
Headers done, handler runningRESPONSE
Response headers sent, body in progressFAILED
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) β
- 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