A modern Python web server and web framework designed for high performance and speed using async/await syntax.
npx @tessl/cli install tessl/pypi-sanic@25.3.0A modern Python 3.8+ web server and web framework designed for high performance and speed. Sanic leverages Python's async/await syntax for non-blocking, asynchronous request handling, making it exceptionally fast for web applications. It's ASGI compliant and includes comprehensive features for building scalable web APIs, microservices, and high-performance web applications.
pip install sanicfrom sanic import SanicCommon imports for web applications:
from sanic import Sanic, Request, Blueprint
from sanic.response import json, text, html, redirect
from sanic.exceptions import NotFound, ServerErrorfrom sanic import Sanic
from sanic.response import json
app = Sanic("MyApp")
@app.route("/")
async def test(request):
return json({"hello": "world"})
@app.route("/user/<name>")
async def user(request, name):
return json({"user": name})
if __name__ == "__main__":
app.run(host="0.0.0.0", port=8000)Sanic's async-first design provides exceptional performance through:
The framework prioritizes speed and efficiency while maintaining developer-friendly APIs and comprehensive feature support.
The main Sanic application class that handles routing, middleware, configuration, and server lifecycle. Provides decorators and methods for defining HTTP routes, WebSocket endpoints, and application behavior.
class Sanic:
def __init__(self, name: str, **kwargs): ...
def route(self, uri: str, methods: list = None, **kwargs): ...
def get(self, uri: str, **kwargs): ...
def post(self, uri: str, **kwargs): ...
def put(self, uri: str, **kwargs): ...
def delete(self, uri: str, **kwargs): ...
def websocket(self, uri: str, **kwargs): ...
def middleware(self, middleware_or_request: str): ...
def run(self, host: str = "127.0.0.1", port: int = 8000, **kwargs): ...Comprehensive request and response objects for handling HTTP communications, including request data parsing, response generation, and specialized response types for different content formats.
class Request:
@property
def json(self): ...
@property
def form(self): ...
@property
def files(self): ...
@property
def args(self): ...
@property
def headers(self): ...
def json(body, **kwargs): ...
def text(body: str, **kwargs): ...
def html(body: str, **kwargs): ...
def raw(body: bytes, **kwargs): ...
def redirect(to: str, **kwargs): ...
def file(location: str, **kwargs): ...
def empty(**kwargs): ...Modular application organization system that allows grouping related routes, middleware, and functionality into reusable components. Supports nested blueprints and blueprint groups for complex application structures.
class Blueprint:
def __init__(self, name: str, **kwargs): ...
def route(self, uri: str, **kwargs): ...
def middleware(self, middleware_or_request: str): ...
def static(self, uri: str, file_or_directory: str, **kwargs): ...
class BlueprintGroup:
def append(self, blueprint: Blueprint): ...
def insert(self, index: int, blueprint: Blueprint): ...Flexible configuration system supporting environment variables, configuration files, and programmatic configuration. Includes built-in configuration options for server behavior, security, and performance tuning.
class Config:
def __init__(self, **kwargs): ...
def load_environment_vars(self, prefix: str = "SANIC_"): ...
def from_envvar(self, variable_name: str): ...
def from_pyfile(self, filename: str): ...
def update_config(self, config: dict): ...Comprehensive exception system with HTTP status code exceptions, error handlers, and custom exception support. Provides both built-in exceptions for common HTTP errors and mechanisms for custom error handling.
class SanicException(Exception): ...
class NotFound(SanicException): ...
class ServerError(SanicException): ...
class BadRequest(SanicException): ...
class Unauthorized(SanicException): ...
class Forbidden(SanicException): ...
def exception(exception_type): ... # decoratorRequest/response middleware pipeline and event-driven signal system for implementing cross-cutting concerns and responding to application lifecycle events.
def middleware(middleware_or_request: str): ... # decorator
class Signal:
def send(self, *args, **kwargs): ...
async def send_async(self, *args, **kwargs): ...Native WebSocket support for real-time, bidirectional communication between client and server. Includes WebSocket routing, connection management, and message handling.
def websocket(uri: str, **kwargs): ... # decorator
class Websocket:
async def send(self, data): ...
async def recv(self): ...
async def ping(self, data: bytes = b""): ...
async def pong(self, data: bytes = b""): ...Server configuration, deployment options, and production-ready features including multi-worker support, SSL/TLS configuration, and various server protocols.
def run(host: str = "127.0.0.1", port: int = 8000, **kwargs): ...
def create_server(**kwargs): ...
def serve(**kwargs): ...# Core type aliases
DefaultSanic = "Sanic[Config, SimpleNamespace]"
DefaultRequest = Request[DefaultSanic, SimpleNamespace]
# Middleware types
MiddlewareType = Callable[[Request, Callable], Awaitable[Optional[HTTPResponse]]]
# Listener types
ListenerType = Callable[[Sanic], Awaitable[None]]
# Handler types
RouteHandler = Callable[..., Awaitable[HTTPResponse]]
# Exception types
class SanicException(Exception): ...
class NotFound(SanicException): ...
class ServerError(SanicException): ...
class BadRequest(SanicException): ...
class Unauthorized(SanicException): ...
class Forbidden(SanicException): ...
class MethodNotAllowed(SanicException): ...
class InvalidHeader(SanicException): ...
class HeaderNotFound(SanicException): ...
class FileNotFound(SanicException): ...
class RangeNotSatisfiable(SanicException): ...
class InternalServerError(SanicException): ...
class ServiceUnavailable(SanicException): ...
class ExpectationFailed(SanicException): ...
# HTTP types
class HTTPMethod:
GET: str = "GET"
POST: str = "POST"
PUT: str = "PUT"
DELETE: str = "DELETE"
PATCH: str = "PATCH"
HEAD: str = "HEAD"
OPTIONS: str = "OPTIONS"
# Configuration and routing
class Config: ...
class Router: ...
class SignalRouter: ...
class ErrorHandler: ...
class Inspector: ...
class CertLoader: ...
# Union types for flexibility
from typing import Union, Optional, Callable, Any, AnyStr