or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

tessl/pypi-uvicorn

The lightning-fast ASGI server.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/uvicorn@0.37.x

To install, run

npx @tessl/cli install tessl/pypi-uvicorn@0.37.0

0

# Uvicorn

1

2

Uvicorn is a lightning-fast ASGI (Asynchronous Server Gateway Interface) server implementation for Python. Built on uvloop and httptools, it provides a high-performance foundation for running asynchronous Python web applications and frameworks like FastAPI, Starlette, and Quart. Uvicorn supports HTTP/1.1, WebSockets, automatic reloading during development, and production-ready multiprocess workers.

3

4

## Package Information

5

6

- **Package Name**: uvicorn

7

- **Package Type**: pypi

8

- **Language**: Python

9

- **Installation**: `pip install uvicorn` or `pip install uvicorn[standard]` (with optional dependencies)

10

11

## Core Imports

12

13

```python

14

import uvicorn

15

```

16

17

Main API components:

18

19

```python

20

from uvicorn import main, run, Config, Server

21

```

22

23

Type definitions for ASGI applications:

24

25

```python

26

from uvicorn._types import (

27

ASGIApplication,

28

ASGI3Application,

29

Scope,

30

HTTPScope,

31

WebSocketScope,

32

ASGIReceiveCallable,

33

ASGISendCallable,

34

)

35

```

36

37

## Basic Usage

38

39

```python

40

import uvicorn

41

42

# Simple ASGI application

43

async def app(scope, receive, send):

44

assert scope['type'] == 'http'

45

await send({

46

'type': 'http.response.start',

47

'status': 200,

48

'headers': [

49

[b'content-type', b'text/plain'],

50

],

51

})

52

await send({

53

'type': 'http.response.body',

54

'body': b'Hello, World!',

55

})

56

57

# Run the server programmatically

58

if __name__ == "__main__":

59

uvicorn.run(app, host="127.0.0.1", port=8000)

60

```

61

62

Using with an import string:

63

64

```python

65

import uvicorn

66

67

# Run an application defined in another module

68

if __name__ == "__main__":

69

uvicorn.run("myapp:app", host="0.0.0.0", port=8000, reload=True)

70

```

71

72

## Architecture

73

74

Uvicorn implements the ASGI specification, which defines a standard interface between Python web servers and applications. The server architecture consists of several key layers:

75

76

### ASGI Protocol

77

78

ASGI (Asynchronous Server Gateway Interface) is a spiritual successor to WSGI, designed for async-capable Python web servers, frameworks, and applications. It provides three distinct connection types:

79

80

- **HTTP**: Request-response cycle for HTTP/1.1 and HTTP/2 connections

81

- **WebSocket**: Bidirectional message-based communication

82

- **Lifespan**: Application startup and shutdown event handling

83

84

Each connection type uses a **scope** (connection metadata), **receive** (incoming messages), and **send** (outgoing messages) pattern.

85

86

### Server Components

87

88

- **Config**: Central configuration object holding all server settings, protocol selections, and runtime parameters

89

- **Server**: Main server class managing the asyncio event loop, socket binding, protocol instances, and graceful shutdown

90

- **ServerState**: Shared state across all protocol connections, tracking active connections and background tasks

91

- **Protocol Implementations**: Pluggable HTTP and WebSocket protocol handlers (h11, httptools, websockets, wsproto)

92

- **Supervisors**: Process management for multiprocess workers and auto-reload during development

93

- **Middleware**: ASGI middleware for proxy headers, ASGI2 compatibility, and WSGI adapter

94

95

This modular design allows Uvicorn to support multiple protocol implementations, graceful configuration updates, and flexible deployment patterns from development to production.

96

97

## Capabilities

98

99

### Running Applications

100

101

The main entry point for running ASGI applications programmatically, with extensive configuration options for protocols, workers, SSL, and more.

102

103

```python { .api }

104

def run(

105

app: ASGIApplication | Callable | str,

106

*,

107

host: str = "127.0.0.1",

108

port: int = 8000,

109

uds: str | None = None,

110

fd: int | None = None,

111

loop: Literal["none", "auto", "asyncio", "uvloop"] | str = "auto",

112

http: Literal["auto", "h11", "httptools"] | str | type[asyncio.Protocol] = "auto",

113

ws: Literal["auto", "none", "websockets", "websockets-sansio", "wsproto"] | str | type[asyncio.Protocol] = "auto",

114

ws_max_size: int = 16777216,

115

ws_max_queue: int = 32,

116

ws_ping_interval: float | None = 20.0,

117

ws_ping_timeout: float | None = 20.0,

118

ws_per_message_deflate: bool = True,

119

lifespan: Literal["auto", "on", "off"] = "auto",

120

interface: Literal["auto", "asgi3", "asgi2", "wsgi"] = "auto",

121

reload: bool = False,

122

reload_dirs: list[str] | str | None = None,

123

reload_includes: list[str] | str | None = None,

124

reload_excludes: list[str] | str | None = None,

125

reload_delay: float = 0.25,

126

workers: int | None = None,

127

env_file: str | os.PathLike | None = None,

128

log_config: dict[str, Any] | str | configparser.RawConfigParser | typing.IO[Any] | None = LOGGING_CONFIG,

129

log_level: str | int | None = None,

130

access_log: bool = True,

131

proxy_headers: bool = True,

132

server_header: bool = True,

133

date_header: bool = True,

134

forwarded_allow_ips: list[str] | str | None = None,

135

root_path: str = "",

136

limit_concurrency: int | None = None,

137

backlog: int = 2048,

138

limit_max_requests: int | None = None,

139

timeout_keep_alive: int = 5,

140

timeout_graceful_shutdown: int | None = None,

141

timeout_worker_healthcheck: int = 5,

142

ssl_keyfile: str | os.PathLike | None = None,

143

ssl_certfile: str | os.PathLike | None = None,

144

ssl_keyfile_password: str | None = None,

145

ssl_version: int = ssl.PROTOCOL_TLS_SERVER,

146

ssl_cert_reqs: int = ssl.CERT_NONE,

147

ssl_ca_certs: str | os.PathLike | None = None,

148

ssl_ciphers: str = "TLSv1",

149

headers: list[tuple[str, str]] | None = None,

150

use_colors: bool | None = None,

151

app_dir: str | None = None,

152

factory: bool = False,

153

h11_max_incomplete_event_size: int | None = None,

154

) -> None:

155

"""

156

Run an ASGI application.

157

158

Args:

159

app: ASGI application instance, factory function, or import string (e.g., "myapp:app")

160

host: Host address to bind

161

port: Port number to bind

162

uds: Unix domain socket path (alternative to host/port)

163

fd: File descriptor for socket binding (alternative to host/port)

164

loop: Event loop implementation

165

http: HTTP protocol implementation

166

ws: WebSocket protocol implementation

167

ws_max_size: Maximum WebSocket message size in bytes

168

ws_max_queue: Maximum WebSocket message queue length

169

ws_ping_interval: WebSocket ping interval in seconds

170

ws_ping_timeout: WebSocket ping timeout in seconds

171

ws_per_message_deflate: Enable WebSocket per-message deflate compression

172

lifespan: Lifespan event handling mode

173

interface: Application interface type (ASGI3, ASGI2, or WSGI)

174

reload: Enable auto-reload on file changes

175

reload_dirs: Directories to watch for changes (defaults to current directory)

176

reload_includes: Glob patterns to include for reload watching

177

reload_excludes: Glob patterns to exclude from reload watching

178

reload_delay: Delay between checking for file changes in seconds

179

workers: Number of worker processes (None for single process)

180

env_file: Path to environment file to load

181

log_config: Logging configuration (dict, file path, or file object)

182

log_level: Logging level (string or int)

183

access_log: Enable access logging

184

proxy_headers: Enable parsing of X-Forwarded-* proxy headers

185

server_header: Include Server header in responses

186

date_header: Include Date header in responses

187

forwarded_allow_ips: IPs to trust for proxy headers (comma-separated or list)

188

root_path: ASGI root_path for mounted applications

189

limit_concurrency: Maximum number of concurrent connections

190

backlog: Socket listen backlog size

191

limit_max_requests: Maximum requests before worker restart

192

timeout_keep_alive: Keep-alive timeout in seconds

193

timeout_graceful_shutdown: Graceful shutdown timeout in seconds

194

timeout_worker_healthcheck: Worker health check timeout in seconds

195

ssl_keyfile: SSL private key file path

196

ssl_certfile: SSL certificate file path

197

ssl_keyfile_password: Password for SSL private key

198

ssl_version: SSL protocol version

199

ssl_cert_reqs: SSL certificate requirements

200

ssl_ca_certs: SSL CA certificates file path

201

ssl_ciphers: SSL cipher configuration

202

headers: Custom default headers to include in all responses

203

use_colors: Enable colored log output (None for auto-detection)

204

app_dir: Directory to add to sys.path before importing app (used by run(), not passed to Config)

205

factory: Treat app as a factory function

206

h11_max_incomplete_event_size: Maximum buffer size for h11 incomplete events

207

"""

208

```

209

210

[Server Configuration](./config.md)

211

212

### Server Lifecycle

213

214

Server class for managing ASGI server lifecycle with async/await support and graceful shutdown handling.

215

216

```python { .api }

217

class Server:

218

"""

219

ASGI server implementation.

220

221

Attributes:

222

config: Server configuration

223

server_state: Shared state across protocol connections

224

started: Whether server has started

225

should_exit: Signal for graceful shutdown

226

force_exit: Signal for immediate shutdown

227

last_notified: Timestamp of last notification (internal use)

228

"""

229

230

def __init__(self, config: Config) -> None:

231

"""

232

Initialize server with configuration.

233

234

Args:

235

config: Server configuration object

236

"""

237

238

def run(self, sockets: list[socket.socket] | None = None) -> None:

239

"""

240

Run server (blocking).

241

242

Args:

243

sockets: Pre-bound sockets (optional)

244

"""

245

246

async def serve(self, sockets: list[socket.socket] | None = None) -> None:

247

"""

248

Run server (async).

249

250

Args:

251

sockets: Pre-bound sockets (optional)

252

"""

253

254

async def startup(self, sockets: list[socket.socket] | None = None) -> None:

255

"""

256

Start the server.

257

258

Args:

259

sockets: Pre-bound sockets (optional)

260

"""

261

262

async def shutdown(self, sockets: list[socket.socket] | None = None) -> None:

263

"""

264

Shutdown the server gracefully.

265

266

Args:

267

sockets: Sockets to close (optional)

268

"""

269

```

270

271

```python { .api }

272

class ServerState:

273

"""

274

Shared state available across all protocol instances.

275

276

Attributes:

277

total_requests: Total number of requests processed

278

connections: Set of active protocol connections

279

tasks: Set of active background tasks

280

default_headers: Default headers to include in responses

281

"""

282

283

total_requests: int

284

connections: set[asyncio.Protocol]

285

tasks: set[asyncio.Task[None]]

286

default_headers: list[tuple[bytes, bytes]]

287

```

288

289

[Server Management](./server.md)

290

291

### Configuration

292

293

Comprehensive configuration class for all server settings, protocol selection, and runtime parameters.

294

295

```python { .api }

296

class Config:

297

"""

298

Server configuration.

299

300

All parameters from run() function are available as constructor parameters.

301

"""

302

303

def __init__(

304

self,

305

app: ASGIApplication | Callable | str,

306

host: str = "127.0.0.1",

307

port: int = 8000,

308

# ... all other parameters same as run() function

309

) -> None:

310

"""Initialize configuration with server settings."""

311

312

@property

313

def asgi_version(self) -> Literal["2.0", "3.0"]:

314

"""Get ASGI version based on interface."""

315

316

@property

317

def is_ssl(self) -> bool:

318

"""Check if SSL is configured."""

319

320

@property

321

def use_subprocess(self) -> bool:

322

"""Check if subprocess mode is used."""

323

324

@property

325

def should_reload(self) -> bool:

326

"""Check if auto-reload should be enabled."""

327

328

def configure_logging(self) -> None:

329

"""Configure the logging system."""

330

331

def load(self) -> None:

332

"""Load application and configure all settings."""

333

334

def bind_socket(self) -> socket.socket:

335

"""Bind and return a socket."""

336

```

337

338

[Configuration Details](./config.md)

339

340

### Logging

341

342

Logging configuration and custom formatters with colored output support.

343

344

```python { .api }

345

class ColourizedFormatter(logging.Formatter):

346

"""

347

Custom log formatter with colored output support.

348

349

Args:

350

fmt: Log format string

351

datefmt: Date format string

352

style: Format style ('%', '{', or '$')

353

use_colors: Enable colored output (None for auto-detection)

354

"""

355

356

def color_level_name(self, level_name: str, level_no: int) -> str:

357

"""Colorize log level name."""

358

359

def should_use_colors(self) -> bool:

360

"""Check if colors should be used."""

361

362

def formatMessage(self, record: logging.LogRecord) -> str:

363

"""Format log record with colors."""

364

```

365

366

```python { .api }

367

class AccessFormatter(ColourizedFormatter):

368

"""

369

Formatter for HTTP access logs.

370

371

Includes status code coloring and HTTP status phrases.

372

"""

373

374

def get_status_code(self, status_code: int) -> str:

375

"""Format status code with HTTP phrase."""

376

```

377

378

[Logging Configuration](./logging.md)

379

380

### Middleware

381

382

ASGI middleware components for proxy headers, protocol adapters, and debugging.

383

384

```python { .api }

385

class ProxyHeadersMiddleware:

386

"""

387

Middleware for handling X-Forwarded-Proto and X-Forwarded-For headers.

388

389

Args:

390

app: ASGI application

391

trusted_hosts: Trusted proxy hosts/networks (comma-separated or list)

392

"""

393

394

def __init__(

395

self,

396

app: ASGI3Application,

397

trusted_hosts: list[str] | str = "127.0.0.1",

398

) -> None: ...

399

400

async def __call__(

401

self,

402

scope: Scope,

403

receive: ASGIReceiveCallable,

404

send: ASGISendCallable,

405

) -> None: ...

406

```

407

408

```python { .api }

409

class ASGI2Middleware:

410

"""

411

Adapter to run ASGI2 applications as ASGI3.

412

413

Args:

414

app: ASGI2 application class

415

"""

416

417

def __init__(self, app: ASGI2Application) -> None: ...

418

419

async def __call__(

420

self,

421

scope: Scope,

422

receive: ASGIReceiveCallable,

423

send: ASGISendCallable,

424

) -> None: ...

425

```

426

427

```python { .api }

428

class WSGIMiddleware:

429

"""

430

Adapter to run WSGI applications in ASGI.

431

432

Args:

433

app: WSGI application

434

workers: Number of worker threads for blocking WSGI calls

435

"""

436

437

def __init__(self, app: WSGIApp, workers: int = 10) -> None: ...

438

439

async def __call__(

440

self,

441

scope: Scope,

442

receive: ASGIReceiveCallable,

443

send: ASGISendCallable,

444

) -> None: ...

445

```

446

447

[Middleware Components](./middleware.md)

448

449

### ASGI Types

450

451

Complete ASGI type definitions for building type-safe applications.

452

453

```python { .api }

454

# Application types

455

ASGIApplication = Union[ASGI2Application, ASGI3Application]

456

ASGI2Application = type[ASGI2Protocol]

457

ASGI3Application = Callable[[Scope, ASGIReceiveCallable, ASGISendCallable], Awaitable[None]]

458

459

# Scope types

460

Scope = Union[HTTPScope, WebSocketScope, LifespanScope]

461

WWWScope = Union[HTTPScope, WebSocketScope]

462

463

# Callable types

464

ASGIReceiveCallable = Callable[[], Awaitable[ASGIReceiveEvent]]

465

ASGISendCallable = Callable[[ASGISendEvent], Awaitable[None]]

466

```

467

468

[Type Definitions](./types.md)

469

470

### Process Management

471

472

Supervisors for multiprocess workers and automatic code reloading during development.

473

474

```python { .api }

475

class Multiprocess:

476

"""

477

Supervisor for managing multiple worker processes.

478

479

Args:

480

config: Server configuration

481

target: Target function to run in each worker

482

sockets: Pre-bound sockets to share across workers

483

"""

484

485

def __init__(

486

self,

487

config: Config,

488

target: Callable,

489

sockets: list[socket.socket],

490

) -> None: ...

491

492

def run(self) -> None:

493

"""Run the multiprocess supervisor."""

494

```

495

496

```python { .api }

497

class BaseReload:

498

"""

499

Base class for reload supervisors.

500

501

Monitors files for changes and restarts the worker process.

502

503

Args:

504

config: Server configuration

505

target: Target function to run

506

sockets: Pre-bound sockets

507

"""

508

509

def run(self) -> None:

510

"""Run the reload supervisor."""

511

```

512

513

[Supervisors](./supervisors.md)

514

515

### Command-Line Interface

516

517

Complete CLI interface for running uvicorn from the command line.

518

519

```bash

520

uvicorn [OPTIONS] APP

521

```

522

523

```python { .api }

524

def main() -> None:

525

"""

526

Main CLI entry point.

527

528

Parses command-line arguments and runs the server.

529

"""

530

```

531

532

[CLI Documentation](./cli.md)

533

534

## Constants

535

536

```python { .api }

537

# Exit codes

538

STARTUP_FAILURE: int = 3

539

540

# Log levels

541

TRACE_LOG_LEVEL: int = 5

542

543

LOG_LEVELS: dict[str, int] = {

544

"critical": logging.CRITICAL,

545

"error": logging.ERROR,

546

"warning": logging.WARNING,

547

"info": logging.INFO,

548

"debug": logging.DEBUG,

549

"trace": TRACE_LOG_LEVEL,

550

}

551

552

# Protocol mappings

553

HTTP_PROTOCOLS: dict[str, str] = {

554

"auto": "uvicorn.protocols.http.auto:AutoHTTPProtocol",

555

"h11": "uvicorn.protocols.http.h11_impl:H11Protocol",

556

"httptools": "uvicorn.protocols.http.httptools_impl:HttpToolsProtocol",

557

}

558

559

WS_PROTOCOLS: dict[str, str | None] = {

560

"auto": "uvicorn.protocols.websockets.auto:AutoWebSocketsProtocol",

561

"none": None,

562

"websockets": "uvicorn.protocols.websockets.websockets_impl:WebSocketProtocol",

563

"websockets-sansio": "uvicorn.protocols.websockets.websockets_sansio_impl:WebSocketsSansIOProtocol",

564

"wsproto": "uvicorn.protocols.websockets.wsproto_impl:WSProtocol",

565

}

566

567

LIFESPAN: dict[str, str] = {

568

"auto": "uvicorn.lifespan.on:LifespanOn",

569

"on": "uvicorn.lifespan.on:LifespanOn",

570

"off": "uvicorn.lifespan.off:LifespanOff",

571

}

572

573

LOOP_FACTORIES: dict[str, str | None] = {

574

"none": None,

575

"auto": "uvicorn.loops.auto:auto_loop_factory",

576

"asyncio": "uvicorn.loops.asyncio:asyncio_loop_factory",

577

"uvloop": "uvicorn.loops.uvloop:uvloop_loop_factory",

578

}

579

```

580

581

## Version

582

583

```python { .api }

584

__version__: str = "0.37.0"

585

```

586