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
npx @tessl/cli install tessl/pypi-hypercorn@0.17.00
# Hypercorn
1
2
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.
3
4
## Package Information
5
6
- **Package Name**: hypercorn
7
- **Language**: Python
8
- **Installation**: `pip install hypercorn`
9
10
## Core Imports
11
12
```python
13
from hypercorn.config import Config
14
from hypercorn.run import run
15
```
16
17
For programmatic usage with async frameworks:
18
19
```python
20
from hypercorn.asyncio import serve
21
from hypercorn.trio import serve
22
```
23
24
## Basic Usage
25
26
### Command Line
27
28
```bash
29
# Basic usage
30
hypercorn app:application
31
32
# With options
33
hypercorn --bind 0.0.0.0:8000 --workers 4 app:application
34
35
# HTTPS with SSL
36
hypercorn --certfile cert.pem --keyfile key.pem app:application
37
```
38
39
### Programmatic Usage
40
41
```python
42
import asyncio
43
from hypercorn.config import Config
44
from hypercorn.asyncio import serve
45
46
# Basic configuration
47
config = Config()
48
config.bind = ["0.0.0.0:8000"]
49
50
# Run ASGI application
51
async def main():
52
await serve(app, config)
53
54
asyncio.run(main())
55
```
56
57
### Configuration
58
59
```python
60
from hypercorn.config import Config
61
62
# From TOML file
63
config = Config.from_toml("hypercorn.toml")
64
65
# From Python file
66
config = Config.from_pyfile("config.py")
67
68
# From dictionary
69
config = Config.from_mapping({
70
"bind": ["0.0.0.0:8000"],
71
"workers": 4,
72
"certfile": "cert.pem",
73
"keyfile": "key.pem"
74
})
75
```
76
77
## Architecture
78
79
Hypercorn's architecture is built around these key components:
80
81
- **Worker Classes**: Support for asyncio, uvloop, and trio event loops
82
- **Protocol Handlers**: HTTP/1, HTTP/2, HTTP/3, and WebSocket protocol implementations
83
- **Application Wrappers**: ASGI and WSGI compatibility layers
84
- **Configuration System**: Comprehensive options for all server aspects
85
- **Event System**: Connection lifecycle and state management
86
- **Middleware**: Built-in components for common server functionality
87
88
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.
89
90
## Capabilities
91
92
### Core Configuration
93
94
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.
95
96
```python { .api }
97
class Config:
98
def __init__(self):
99
# Core binding options
100
self.bind: list[str]
101
self.insecure_bind: list[str]
102
self.quic_bind: list[str]
103
104
# SSL/TLS settings
105
self.certfile: str | None
106
self.keyfile: str | None
107
self.ca_certs: str | None
108
self.ciphers: str
109
110
# Server behavior
111
self.workers: int
112
self.worker_class: str
113
self.backlog: int
114
self.graceful_timeout: int
115
self.keep_alive_timeout: int
116
117
@classmethod
118
def from_mapping(cls, mapping: dict) -> Config: ...
119
@classmethod
120
def from_pyfile(cls, filename: str) -> Config: ...
121
@classmethod
122
def from_toml(cls, filename: str) -> Config: ...
123
124
def create_ssl_context(self) -> ssl.SSLContext | None: ...
125
def create_sockets(self) -> Sockets: ...
126
```
127
128
[Configuration](./configuration.md)
129
130
### Server Execution
131
132
Core server execution functions for running Hypercorn from code or command line, supporting both programmatic and CLI interfaces with full configuration options.
133
134
```python { .api }
135
def run(config: Config) -> int: ...
136
def main(sys_args: list[str] | None = None) -> int: ...
137
```
138
139
[Server Execution](./server-execution.md)
140
141
### Async Framework Integration
142
143
Programmatic interfaces for serving ASGI and WSGI applications with asyncio and trio event loops, providing fine-grained control over server lifecycle and shutdown handling.
144
145
```python { .api }
146
# Asyncio integration
147
async def serve(
148
app: ASGIFramework | WSGIFramework,
149
config: Config,
150
shutdown_trigger: Callable[..., Awaitable[None]] | None = None,
151
mode: str | None = None
152
) -> None: ...
153
154
# Trio integration
155
async def serve(
156
app: ASGIFramework | WSGIFramework,
157
config: Config,
158
shutdown_trigger: Callable[..., Awaitable[None]] | None = None,
159
task_status: TaskStatus = TASK_STATUS_IGNORED,
160
mode: str | None = None
161
) -> None: ...
162
```
163
164
[Async Integration](./async-integration.md)
165
166
### Application Wrappers
167
168
Wrapper classes that adapt ASGI and WSGI applications to Hypercorn's internal protocol interface, handling protocol translation and request/response lifecycle.
169
170
```python { .api }
171
class ASGIWrapper:
172
def __init__(self, app: ASGIFramework): ...
173
async def __call__(
174
self,
175
scope: Scope,
176
receive: ASGIReceiveCallable,
177
send: ASGISendCallable,
178
sync_spawn: Callable,
179
call_soon: Callable
180
): ...
181
182
class WSGIWrapper:
183
def __init__(self, app: WSGIFramework, max_body_size: int): ...
184
async def __call__(
185
self,
186
scope: Scope,
187
receive: ASGIReceiveCallable,
188
send: ASGISendCallable,
189
sync_spawn: Callable,
190
call_soon: Callable
191
): ...
192
```
193
194
[Application Wrappers](./application-wrappers.md)
195
196
### Middleware Components
197
198
Built-in middleware for common server functionality including WSGI adaptation, request routing, HTTPS redirection, and proxy header handling.
199
200
```python { .api }
201
class AsyncioWSGIMiddleware: ...
202
class TrioWSGIMiddleware: ...
203
class DispatcherMiddleware: ...
204
class HTTPToHTTPSRedirectMiddleware: ...
205
class ProxyFixMiddleware: ...
206
```
207
208
[Middleware](./middleware.md)
209
210
### Logging System
211
212
Comprehensive logging framework with access log formatting, structured logging, and StatsD metrics integration for monitoring and observability.
213
214
```python { .api }
215
class Logger:
216
def __init__(self, config: Config): ...
217
async def critical(self, message: str, *args, **kwargs): ...
218
async def error(self, message: str, *args, **kwargs): ...
219
async def warning(self, message: str, *args, **kwargs): ...
220
async def info(self, message: str, *args, **kwargs): ...
221
async def debug(self, message: str, *args, **kwargs): ...
222
async def access(self, request, response, request_time: float): ...
223
224
class StatsdLogger(Logger):
225
def increment(self, name: str, value: int = 1, tags: dict | None = None): ...
226
def decrement(self, name: str, value: int = 1, tags: dict | None = None): ...
227
def histogram(self, name: str, value: float, tags: dict | None = None): ...
228
def gauge(self, name: str, value: float, tags: dict | None = None): ...
229
```
230
231
[Logging](./logging.md)
232
233
### Utilities and Helpers
234
235
Utility functions for application loading, file monitoring, address parsing, header processing, and other common server operations.
236
237
```python { .api }
238
def load_application(path: str, wsgi_max_body_size: int): ...
239
def wrap_app(app, wsgi_max_body_size: int, mode: str | None = None): ...
240
def files_to_watch() -> list[str]: ...
241
def check_for_updates(files: list[str]) -> bool: ...
242
def write_pid_file(pid_path: str): ...
243
def parse_socket_addr(family: int, address: tuple): ...
244
def repr_socket_addr(family: int, address: tuple) -> str: ...
245
def valid_server_name(config: Config, request) -> bool: ...
246
def is_asgi(app) -> bool: ...
247
```
248
249
[Utilities](./utilities.md)
250
251
### Type Definitions
252
253
Comprehensive type definitions for ASGI protocol compliance, including scope definitions, event types, callable interfaces, and protocol specifications for type-safe development.
254
255
```python { .api }
256
# ASGI Scopes
257
class HTTPScope(TypedDict): ...
258
class WebsocketScope(TypedDict): ...
259
class LifespanScope(TypedDict): ...
260
261
# ASGI Events
262
class HTTPRequestEvent(TypedDict): ...
263
class HTTPResponseStartEvent(TypedDict): ...
264
class WebsocketConnectEvent(TypedDict): ...
265
266
# ASGI Callables
267
ASGIReceiveCallable = Callable[[], Awaitable[ASGIReceiveEvent]]
268
ASGISendCallable = Callable[[ASGISendEvent], Awaitable[None]]
269
270
# Framework Types
271
ASGIFramework = Callable[[Scope, ASGIReceiveCallable, ASGISendCallable], Awaitable[None]]
272
WSGIFramework = Callable[[dict, Callable], Iterable[bytes]]
273
```
274
275
[Types](./types.md)
276
277
### Event System
278
279
Event-driven architecture for connection lifecycle management, providing structured event handling for connection state changes and data flow.
280
281
```python { .api }
282
class Event(ABC): ...
283
284
@dataclass
285
class RawData(Event):
286
data: bytes
287
address: tuple | None = None
288
289
@dataclass
290
class Closed(Event): ...
291
292
@dataclass
293
class Updated(Event):
294
idle: bool
295
```
296
297
[Events](./events.md)