or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

blueprints.mdconfiguration.mdcore-application.mdexceptions.mdindex.mdmiddleware-signals.mdrequest-response.mdserver-deployment.mdwebsockets.md
tile.json

tessl/pypi-sanic

A modern Python web server and web framework designed for high performance and speed using async/await syntax.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/sanic@25.3.x

To install, run

npx @tessl/cli install tessl/pypi-sanic@25.3.0

index.mddocs/

Sanic

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

Package Information

  • Package Name: sanic
  • Language: Python
  • Installation: pip install sanic
  • Python Requirements: Python 3.8+

Core Imports

from sanic import Sanic

Common imports for web applications:

from sanic import Sanic, Request, Blueprint
from sanic.response import json, text, html, redirect
from sanic.exceptions import NotFound, ServerError

Basic Usage

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

Architecture

Sanic's async-first design provides exceptional performance through:

  • Async/Await Support: Native Python async/await for non-blocking operations
  • ASGI Compliance: Standard interface for asynchronous web servers and applications
  • Optimized Libraries: Uses uvloop and ujson by default for maximum performance
  • Modular Design: Blueprint system for organizing large applications
  • Middleware Pipeline: Request/response processing pipeline for cross-cutting concerns
  • Signal System: Event-driven programming with built-in and custom signals

The framework prioritizes speed and efficiency while maintaining developer-friendly APIs and comprehensive feature support.

Capabilities

Core Application

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

Core Application

Request and Response Handling

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

Request and Response

Blueprint System

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

Blueprint System

Configuration Management

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

Configuration

Exception Handling

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): ...  # decorator

Exception Handling

Middleware and Signals

Request/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): ...

Middleware and Signals

WebSocket Support

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

WebSocket Support

Server and Deployment

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

Server and Deployment

Types

# 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