or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

application-wrappers.mdasync-integration.mdconfiguration.mdevents.mdindex.mdlogging.mdmiddleware.mdserver-execution.mdtypes.mdutilities.md
tile.json

tessl/pypi-hypercorn

A high-performance ASGI and WSGI web server implementation that provides comprehensive support for modern web protocols including HTTP/1, HTTP/2, WebSockets, and experimental HTTP/3

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/hypercorn@0.17.x

To install, run

npx @tessl/cli install tessl/pypi-hypercorn@0.17.0

index.mddocs/

Hypercorn

A high-performance ASGI and WSGI web server implementation that provides comprehensive support for modern web protocols including HTTP/1, HTTP/2, WebSockets, and experimental HTTP/3. Built on robust sans-io libraries (h11, h2, wsproto, aioquic), it serves as a production-ready alternative to Gunicorn with enhanced async capabilities.

Package Information

  • Package Name: hypercorn
  • Language: Python
  • Installation: pip install hypercorn

Core Imports

from hypercorn.config import Config
from hypercorn.run import run

For programmatic usage with async frameworks:

from hypercorn.asyncio import serve
from hypercorn.trio import serve

Basic Usage

Command Line

# Basic usage
hypercorn app:application

# With options
hypercorn --bind 0.0.0.0:8000 --workers 4 app:application

# HTTPS with SSL
hypercorn --certfile cert.pem --keyfile key.pem app:application

Programmatic Usage

import asyncio
from hypercorn.config import Config
from hypercorn.asyncio import serve

# Basic configuration
config = Config()
config.bind = ["0.0.0.0:8000"]

# Run ASGI application
async def main():
    await serve(app, config)

asyncio.run(main())

Configuration

from hypercorn.config import Config

# From TOML file
config = Config.from_toml("hypercorn.toml")

# From Python file
config = Config.from_pyfile("config.py")

# From dictionary
config = Config.from_mapping({
    "bind": ["0.0.0.0:8000"],
    "workers": 4,
    "certfile": "cert.pem",
    "keyfile": "key.pem"
})

Architecture

Hypercorn's architecture is built around these key components:

  • Worker Classes: Support for asyncio, uvloop, and trio event loops
  • Protocol Handlers: HTTP/1, HTTP/2, HTTP/3, and WebSocket protocol implementations
  • Application Wrappers: ASGI and WSGI compatibility layers
  • Configuration System: Comprehensive options for all server aspects
  • Event System: Connection lifecycle and state management
  • Middleware: Built-in components for common server functionality

The server can operate in single-worker or multi-worker modes, with each worker handling connections asynchronously. The modular design allows for extensive customization while maintaining high performance for modern async Python applications.

Capabilities

Core Configuration

Primary configuration system with comprehensive server options, SSL/TLS settings, logging configuration, and deployment parameters. The Config class provides the foundation for all server behavior.

class Config:
    def __init__(self):
        # Core binding options
        self.bind: list[str]
        self.insecure_bind: list[str] 
        self.quic_bind: list[str]
        
        # SSL/TLS settings
        self.certfile: str | None
        self.keyfile: str | None
        self.ca_certs: str | None
        self.ciphers: str
        
        # Server behavior
        self.workers: int
        self.worker_class: str
        self.backlog: int
        self.graceful_timeout: int
        self.keep_alive_timeout: int
        
    @classmethod
    def from_mapping(cls, mapping: dict) -> Config: ...
    @classmethod
    def from_pyfile(cls, filename: str) -> Config: ...
    @classmethod
    def from_toml(cls, filename: str) -> Config: ...
    
    def create_ssl_context(self) -> ssl.SSLContext | None: ...
    def create_sockets(self) -> Sockets: ...

Configuration

Server Execution

Core server execution functions for running Hypercorn from code or command line, supporting both programmatic and CLI interfaces with full configuration options.

def run(config: Config) -> int: ...
def main(sys_args: list[str] | None = None) -> int: ...

Server Execution

Async Framework Integration

Programmatic interfaces for serving ASGI and WSGI applications with asyncio and trio event loops, providing fine-grained control over server lifecycle and shutdown handling.

# Asyncio integration
async def serve(
    app: ASGIFramework | WSGIFramework,
    config: Config,
    shutdown_trigger: Callable[..., Awaitable[None]] | None = None,
    mode: str | None = None
) -> None: ...

# Trio integration  
async def serve(
    app: ASGIFramework | WSGIFramework,
    config: Config,
    shutdown_trigger: Callable[..., Awaitable[None]] | None = None,
    task_status: TaskStatus = TASK_STATUS_IGNORED,
    mode: str | None = None
) -> None: ...

Async Integration

Application Wrappers

Wrapper classes that adapt ASGI and WSGI applications to Hypercorn's internal protocol interface, handling protocol translation and request/response lifecycle.

class ASGIWrapper:
    def __init__(self, app: ASGIFramework): ...
    async def __call__(
        self, 
        scope: Scope, 
        receive: ASGIReceiveCallable, 
        send: ASGISendCallable,
        sync_spawn: Callable,
        call_soon: Callable
    ): ...

class WSGIWrapper:
    def __init__(self, app: WSGIFramework, max_body_size: int): ...
    async def __call__(
        self,
        scope: Scope,
        receive: ASGIReceiveCallable,
        send: ASGISendCallable, 
        sync_spawn: Callable,
        call_soon: Callable
    ): ...

Application Wrappers

Middleware Components

Built-in middleware for common server functionality including WSGI adaptation, request routing, HTTPS redirection, and proxy header handling.

class AsyncioWSGIMiddleware: ...
class TrioWSGIMiddleware: ...
class DispatcherMiddleware: ...
class HTTPToHTTPSRedirectMiddleware: ...
class ProxyFixMiddleware: ...

Middleware

Logging System

Comprehensive logging framework with access log formatting, structured logging, and StatsD metrics integration for monitoring and observability.

class Logger:
    def __init__(self, config: Config): ...
    async def critical(self, message: str, *args, **kwargs): ...
    async def error(self, message: str, *args, **kwargs): ...
    async def warning(self, message: str, *args, **kwargs): ...
    async def info(self, message: str, *args, **kwargs): ...
    async def debug(self, message: str, *args, **kwargs): ...
    async def access(self, request, response, request_time: float): ...

class StatsdLogger(Logger):
    def increment(self, name: str, value: int = 1, tags: dict | None = None): ...
    def decrement(self, name: str, value: int = 1, tags: dict | None = None): ...
    def histogram(self, name: str, value: float, tags: dict | None = None): ...
    def gauge(self, name: str, value: float, tags: dict | None = None): ...

Logging

Utilities and Helpers

Utility functions for application loading, file monitoring, address parsing, header processing, and other common server operations.

def load_application(path: str, wsgi_max_body_size: int): ...
def wrap_app(app, wsgi_max_body_size: int, mode: str | None = None): ...
def files_to_watch() -> list[str]: ...
def check_for_updates(files: list[str]) -> bool: ...
def write_pid_file(pid_path: str): ...
def parse_socket_addr(family: int, address: tuple): ...
def repr_socket_addr(family: int, address: tuple) -> str: ...
def valid_server_name(config: Config, request) -> bool: ...
def is_asgi(app) -> bool: ...

Utilities

Type Definitions

Comprehensive type definitions for ASGI protocol compliance, including scope definitions, event types, callable interfaces, and protocol specifications for type-safe development.

# ASGI Scopes
class HTTPScope(TypedDict): ...
class WebsocketScope(TypedDict): ...
class LifespanScope(TypedDict): ...

# ASGI Events
class HTTPRequestEvent(TypedDict): ...
class HTTPResponseStartEvent(TypedDict): ...
class WebsocketConnectEvent(TypedDict): ...

# ASGI Callables
ASGIReceiveCallable = Callable[[], Awaitable[ASGIReceiveEvent]]
ASGISendCallable = Callable[[ASGISendEvent], Awaitable[None]]

# Framework Types
ASGIFramework = Callable[[Scope, ASGIReceiveCallable, ASGISendCallable], Awaitable[None]]
WSGIFramework = Callable[[dict, Callable], Iterable[bytes]]

Types

Event System

Event-driven architecture for connection lifecycle management, providing structured event handling for connection state changes and data flow.

class Event(ABC): ...

@dataclass
class RawData(Event):
    data: bytes
    address: tuple | None = None

@dataclass  
class Closed(Event): ...

@dataclass
class Updated(Event):
    idle: bool

Events