or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

cli.mdconfig.mdindex.mdlogging.mdmiddleware.mdserver.mdsupervisors.mdtypes.md

config.mddocs/

0

# Server Configuration

1

2

Comprehensive configuration system for uvicorn server settings. The `Config` class holds all server parameters, protocol selections, and runtime settings, providing properties and methods for configuration loading and validation.

3

4

## Imports

5

6

```python

7

from uvicorn import Config

8

from uvicorn.config import (

9

create_ssl_context,

10

HTTPProtocolType,

11

WSProtocolType,

12

LifespanType,

13

LoopFactoryType,

14

InterfaceType,

15

)

16

```

17

18

## Capabilities

19

20

### Configuration Class

21

22

Central configuration object that holds all server settings and provides methods for loading and validation.

23

24

```python { .api }

25

class Config:

26

"""

27

Server configuration for uvicorn.

28

29

Holds all server settings including network binding, protocol selection,

30

worker configuration, SSL/TLS, logging, timeouts, and runtime behavior.

31

"""

32

33

def __init__(

34

self,

35

app: ASGIApplication | Callable | str,

36

host: str = "127.0.0.1",

37

port: int = 8000,

38

uds: str | None = None,

39

fd: int | None = None,

40

loop: LoopFactoryType | str = "auto",

41

http: HTTPProtocolType | str | type[asyncio.Protocol] = "auto",

42

ws: WSProtocolType | str | type[asyncio.Protocol] = "auto",

43

ws_max_size: int = 16777216,

44

ws_max_queue: int = 32,

45

ws_ping_interval: float | None = 20.0,

46

ws_ping_timeout: float | None = 20.0,

47

ws_per_message_deflate: bool = True,

48

lifespan: LifespanType = "auto",

49

interface: InterfaceType = "auto",

50

reload: bool = False,

51

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

52

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

53

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

54

reload_delay: float = 0.25,

55

workers: int | None = None,

56

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

57

log_config: dict | str | configparser.RawConfigParser | typing.IO | None = None,

58

log_level: str | int | None = None,

59

access_log: bool = True,

60

proxy_headers: bool = True,

61

server_header: bool = True,

62

date_header: bool = True,

63

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

64

root_path: str = "",

65

limit_concurrency: int | None = None,

66

backlog: int = 2048,

67

limit_max_requests: int | None = None,

68

timeout_keep_alive: int = 5,

69

timeout_notify: int = 30,

70

timeout_graceful_shutdown: int | None = None,

71

timeout_worker_healthcheck: int = 5,

72

callback_notify: Callable[..., Awaitable[None]] | None = None,

73

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

74

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

75

ssl_keyfile_password: str | None = None,

76

ssl_version: int = ssl.PROTOCOL_TLS_SERVER,

77

ssl_cert_reqs: int = ssl.CERT_NONE,

78

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

79

ssl_ciphers: str = "TLSv1",

80

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

81

use_colors: bool | None = None,

82

factory: bool = False,

83

h11_max_incomplete_event_size: int | None = None,

84

) -> None:

85

"""

86

Initialize server configuration.

87

88

Args:

89

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

90

host: Bind socket to this host address (default: "127.0.0.1")

91

port: Bind socket to this port (default: 8000)

92

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

93

fd: Use file descriptor for socket (alternative to host/port)

94

loop: Event loop implementation ("none", "auto", "asyncio", "uvloop")

95

http: HTTP protocol implementation ("auto", "h11", "httptools") or protocol class

96

ws: WebSocket protocol implementation ("auto", "none", "websockets", "websockets-sansio", "wsproto") or protocol class

97

ws_max_size: Maximum WebSocket message size in bytes (default: 16777216)

98

ws_max_queue: Maximum WebSocket message queue length (default: 32)

99

ws_ping_interval: WebSocket ping interval in seconds (default: 20.0, None to disable)

100

ws_ping_timeout: WebSocket ping timeout in seconds (default: 20.0, None to disable)

101

ws_per_message_deflate: Enable WebSocket per-message deflate compression (default: True)

102

lifespan: Lifespan event handling mode ("auto", "on", "off")

103

interface: Application interface type ("auto", "asgi3", "asgi2", "wsgi")

104

reload: Enable auto-reload on file changes (default: False)

105

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

106

reload_includes: Glob patterns to include for reload watching

107

reload_excludes: Glob patterns to exclude from reload watching

108

reload_delay: Delay between checking for file changes in seconds (default: 0.25)

109

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

110

env_file: Path to environment file to load (.env file)

111

log_config: Logging configuration as dict, file path (.json, .yaml, .ini), or file object

112

log_level: Logging level as string ("critical", "error", "warning", "info", "debug", "trace") or int

113

access_log: Enable HTTP access logging (default: True)

114

proxy_headers: Enable parsing of X-Forwarded-* proxy headers (default: True)

115

server_header: Include Server header in HTTP responses (default: True)

116

date_header: Include Date header in HTTP responses (default: True)

117

forwarded_allow_ips: Comma-separated string or list of IPs to trust for proxy headers

118

root_path: ASGI root_path for applications mounted at a path (default: "")

119

limit_concurrency: Maximum number of concurrent connections (None for unlimited)

120

backlog: Socket listen backlog size (default: 2048)

121

limit_max_requests: Maximum requests before worker restart (None for unlimited)

122

timeout_keep_alive: HTTP keep-alive connection timeout in seconds (default: 5)

123

timeout_notify: Maximum time to wait for graceful shutdown notification in seconds (default: 30)

124

timeout_graceful_shutdown: Graceful shutdown timeout in seconds (None for unlimited)

125

timeout_worker_healthcheck: Worker health check timeout in seconds (default: 5)

126

callback_notify: Async callback function to invoke during graceful shutdown

127

ssl_keyfile: Path to SSL/TLS private key file

128

ssl_certfile: Path to SSL/TLS certificate file

129

ssl_keyfile_password: Password for encrypted SSL/TLS private key

130

ssl_version: SSL/TLS protocol version (default: ssl.PROTOCOL_TLS_SERVER)

131

ssl_cert_reqs: SSL/TLS certificate requirements (default: ssl.CERT_NONE)

132

ssl_ca_certs: Path to SSL/TLS CA certificates file for client verification

133

ssl_ciphers: SSL/TLS cipher configuration string (default: "TLSv1")

134

headers: List of custom default headers to include in all responses as (name, value) tuples

135

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

136

factory: Treat app as a factory function that returns ASGI application (default: False)

137

h11_max_incomplete_event_size: Maximum buffer size for h11 incomplete events in bytes (None for unlimited)

138

"""

139

140

@property

141

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

142

"""

143

Get ASGI version based on interface configuration.

144

145

**NOTE**: If interface is "auto", this property requires load() to have been called

146

first to auto-detect the interface type. Otherwise it will use the configured

147

interface value.

148

149

Returns:

150

"2.0" for ASGI2 interface, "3.0" for ASGI3/WSGI/auto interfaces

151

"""

152

153

@property

154

def is_ssl(self) -> bool:

155

"""

156

Check if SSL/TLS is configured.

157

158

Returns:

159

True if SSL key and certificate files are provided

160

"""

161

162

@property

163

def use_subprocess(self) -> bool:

164

"""

165

Check if subprocess mode should be used.

166

167

Returns:

168

True if workers > 1 or reload is enabled with workers specified

169

"""

170

171

@property

172

def should_reload(self) -> bool:

173

"""

174

Check if auto-reload should be enabled.

175

176

Returns:

177

True if reload is enabled AND app is a string (import path).

178

Auto-reload requires a string import path to re-import the app on changes.

179

"""

180

181

def configure_logging(self) -> None:

182

"""

183

Configure Python logging system with uvicorn's logging configuration.

184

185

Sets up log levels, handlers, formatters, and colored output based on

186

log_config, log_level, access_log, and use_colors settings.

187

"""

188

189

def load(self) -> None:

190

"""

191

Load application and configure all settings.

192

193

**CRITICAL**: This method must be called before using Config with Server.startup().

194

The load() method initializes internal state required by the Server class.

195

196

**NOTE**: load() is automatically called by uvicorn.run() and Server.serve(),

197

so you only need to call it manually when using Server.startup() directly.

198

199

This method:

200

- Creates SSL context if SSL is configured (sets self.ssl)

201

- Encodes headers to bytes (sets self.encoded_headers)

202

- Imports and instantiates protocol classes (sets self.http_protocol_class, self.ws_protocol_class)

203

- Imports lifespan class (sets self.lifespan_class)

204

- Imports the application from string if needed (sets self.loaded_app)

205

- Applies WSGI/ASGI2/proxy headers middleware if configured

206

- Auto-detects interface type (asgi2/asgi3) if set to "auto"

207

- Sets self.loaded = True to indicate configuration is ready

208

209

After calling load():

210

- self.loaded: True

211

- self.loaded_app: The loaded ASGI application (possibly wrapped in middleware)

212

- self.http_protocol_class: HTTP protocol class

213

- self.ws_protocol_class: WebSocket protocol class (or None)

214

- self.lifespan_class: Lifespan handler class

215

- self.ssl: SSL context (or None)

216

- self.encoded_headers: List of byte-encoded headers

217

218

Raises:

219

SystemExit: If application import fails or factory loading fails

220

AssertionError: If called when already loaded

221

"""

222

223

def get_loop_factory(self) -> Callable[[], asyncio.AbstractEventLoop] | None:

224

"""

225

Get the event loop factory based on loop configuration.

226

227

Returns:

228

Event loop factory function, or None if loop is "none"

229

230

The loop factory is resolved from:

231

- Built-in loop types: "auto", "asyncio", "uvloop"

232

- Custom loop factory import string

233

- None for "none" (no event loop setup)

234

235

This method is used internally by uvicorn to set up the event loop.

236

For "auto" mode, uvloop is used if available, otherwise asyncio.

237

"""

238

239

def bind_socket(self) -> socket.socket:

240

"""

241

Create and bind a socket based on configuration.

242

243

Returns:

244

Bound socket ready for listening

245

246

The socket is bound using:

247

- Unix domain socket if uds is configured

248

- File descriptor if fd is configured

249

- TCP socket on host:port otherwise

250

251

Socket options are set for reuse and configured with backlog size.

252

"""

253

```

254

255

### Configuration Type Aliases

256

257

Type definitions for configuration string literals.

258

259

```python { .api }

260

# HTTP protocol implementation type

261

HTTPProtocolType = Literal["auto", "h11", "httptools"]

262

263

# WebSocket protocol implementation type

264

WSProtocolType = Literal["auto", "none", "websockets", "websockets-sansio", "wsproto"]

265

266

# Lifespan event handling type

267

LifespanType = Literal["auto", "on", "off"]

268

269

# Event loop implementation type

270

LoopFactoryType = Literal["none", "auto", "asyncio", "uvloop"]

271

272

# ASGI interface type

273

InterfaceType = Literal["auto", "asgi3", "asgi2", "wsgi"]

274

```

275

276

### SSL Context Creation

277

278

Helper function for creating SSL contexts.

279

280

```python { .api }

281

def create_ssl_context(

282

certfile: str | os.PathLike[str],

283

keyfile: str | os.PathLike[str] | None,

284

password: str | None,

285

ssl_version: int,

286

cert_reqs: int,

287

ca_certs: str | os.PathLike[str] | None,

288

ciphers: str | None,

289

) -> ssl.SSLContext:

290

"""

291

Create and configure an SSL context for HTTPS/WSS connections.

292

293

Args:

294

certfile: Path to SSL/TLS certificate file

295

keyfile: Path to SSL/TLS private key file (None to use certfile)

296

password: Password for encrypted private key (None if not encrypted)

297

ssl_version: SSL/TLS protocol version

298

cert_reqs: Certificate requirements for client verification

299

ca_certs: Path to CA certificates file for verifying client certificates (None if not needed)

300

ciphers: Cipher suite configuration string (None to use defaults)

301

302

Returns:

303

Configured SSLContext ready for use with server sockets

304

"""

305

```

306

307

### Configuration Attributes

308

309

After calling `load()`, the Config instance has additional attributes set:

310

311

```python { .api }

312

class Config:

313

# Attributes set after load() is called

314

loaded: bool

315

"""Whether load() has been called."""

316

317

encoded_headers: list[tuple[bytes, bytes]]

318

"""HTTP headers encoded as bytes."""

319

320

ssl: ssl.SSLContext | None

321

"""SSL context if SSL is configured."""

322

323

http_protocol_class: type[asyncio.Protocol]

324

"""Resolved HTTP protocol implementation class."""

325

326

ws_protocol_class: type[asyncio.Protocol] | None

327

"""Resolved WebSocket protocol implementation class (None if ws="none")."""

328

329

lifespan_class: type

330

"""Resolved lifespan handler class."""

331

332

loaded_app: ASGIApplication

333

"""Loaded ASGI application instance."""

334

```

335

336

## Configuration Constants

337

338

```python { .api }

339

# Default log levels mapping

340

LOG_LEVELS: dict[str, int] = {

341

"critical": logging.CRITICAL, # 50

342

"error": logging.ERROR, # 40

343

"warning": logging.WARNING, # 30

344

"info": logging.INFO, # 20

345

"debug": logging.DEBUG, # 10

346

"trace": 5, # Custom trace level

347

}

348

349

# HTTP protocol implementation mappings

350

HTTP_PROTOCOLS: dict[str, str] = {

351

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

352

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

353

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

354

}

355

356

# WebSocket protocol implementation mappings

357

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

358

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

359

"none": None,

360

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

361

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

362

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

363

}

364

365

# Lifespan handler mappings

366

LIFESPAN: dict[str, str] = {

367

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

368

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

369

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

370

}

371

372

# Event loop factory mappings

373

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

374

"none": None,

375

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

376

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

377

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

378

}

379

380

# Available ASGI interfaces

381

INTERFACES: list[InterfaceType] = ["auto", "asgi3", "asgi2", "wsgi"]

382

383

# Default SSL protocol version

384

SSL_PROTOCOL_VERSION: int = ssl.PROTOCOL_TLS_SERVER

385

386

# Default logging configuration dictionary

387

LOGGING_CONFIG: dict[str, Any]

388

"""

389

Default logging configuration used when log_config is not specified.

390

Configures formatters, handlers, and loggers for uvicorn and access logs.

391

"""

392

```

393

394

## Usage Examples

395

396

### Basic Configuration

397

398

```python

399

from uvicorn import Config, Server

400

401

# Create configuration

402

config = Config(

403

app="myapp:app",

404

host="0.0.0.0",

405

port=8000,

406

log_level="info",

407

)

408

409

# Load configuration

410

config.load()

411

412

# Use with server

413

server = Server(config)

414

server.run()

415

```

416

417

### SSL/TLS Configuration

418

419

```python

420

from uvicorn import Config

421

import ssl

422

423

config = Config(

424

app="myapp:app",

425

host="0.0.0.0",

426

port=443,

427

ssl_keyfile="/path/to/key.pem",

428

ssl_certfile="/path/to/cert.pem",

429

ssl_version=ssl.PROTOCOL_TLS_SERVER,

430

ssl_cert_reqs=ssl.CERT_NONE,

431

)

432

config.load()

433

```

434

435

### Development with Auto-Reload

436

437

```python

438

from uvicorn import Config

439

440

config = Config(

441

app="myapp:app",

442

reload=True,

443

reload_dirs=["./src", "./lib"],

444

reload_includes=["*.py", "*.yaml"],

445

reload_excludes=["*.pyc", "__pycache__/*"],

446

reload_delay=0.5,

447

)

448

config.load()

449

```

450

451

### Production with Multiple Workers

452

453

```python

454

from uvicorn import Config

455

456

config = Config(

457

app="myapp:app",

458

host="0.0.0.0",

459

port=8000,

460

workers=4,

461

limit_concurrency=1000,

462

limit_max_requests=10000,

463

timeout_keep_alive=5,

464

timeout_graceful_shutdown=30,

465

access_log=True,

466

)

467

config.load()

468

```

469

470

### Custom Logging Configuration

471

472

```python

473

from uvicorn import Config

474

475

logging_config = {

476

"version": 1,

477

"disable_existing_loggers": False,

478

"formatters": {

479

"default": {

480

"format": "%(asctime)s - %(name)s - %(levelname)s - %(message)s",

481

},

482

},

483

"handlers": {

484

"default": {

485

"formatter": "default",

486

"class": "logging.StreamHandler",

487

"stream": "ext://sys.stdout",

488

},

489

},

490

"loggers": {

491

"uvicorn": {"handlers": ["default"], "level": "INFO"},

492

"uvicorn.access": {"handlers": ["default"], "level": "INFO"},

493

},

494

}

495

496

config = Config(

497

app="myapp:app",

498

log_config=logging_config,

499

)

500

config.load()

501

```

502

503

### Protocol Selection

504

505

```python

506

from uvicorn import Config

507

508

# Use specific HTTP protocol

509

config = Config(

510

app="myapp:app",

511

http="h11", # or "httptools"

512

ws="websockets", # or "wsproto", "none"

513

)

514

config.load()

515

516

# Use custom protocol class

517

from uvicorn.protocols.http.h11_impl import H11Protocol

518

519

config = Config(

520

app="myapp:app",

521

http=H11Protocol,

522

)

523

config.load()

524

```

525

526

### Proxy Configuration

527

528

```python

529

from uvicorn import Config

530

531

config = Config(

532

app="myapp:app",

533

proxy_headers=True,

534

forwarded_allow_ips="127.0.0.1,10.0.0.0/8",

535

root_path="/api/v1",

536

)

537

config.load()

538

```

539

540

### WebSocket Configuration

541

542

```python

543

from uvicorn import Config

544

545

config = Config(

546

app="myapp:app",

547

ws="websockets",

548

ws_max_size=16 * 1024 * 1024, # 16 MB

549

ws_max_queue=32,

550

ws_ping_interval=20.0,

551

ws_ping_timeout=20.0,

552

ws_per_message_deflate=True,

553

)

554

config.load()

555

```

556