CLI & Configuration
Relevant source files
The following files were used as context for generating this wiki page:
The CLI and Configuration system in Uvicorn provides a robust interface for defining server behavior, ranging from network socket binding to protocol implementation choices and process management. It bridges the gap between the end-user's command-line input and the internal Server state.
This system is built primarily on the click library for the Command Line Interface (CLI) and a centralized Config class that validates and stores all operational parameters. It supports various configuration methods including command-line arguments, environment variables, and .env files.
Sources: uvicorn/main.py:1-60, uvicorn/config.py:1-150, pyproject.toml:68-69
CLI Architecture and Entry Points
The primary entry point for the application is defined in pyproject.toml as the uvicorn script, which points to the main function in uvicorn/main.py. The CLI uses decorators from the click library to define options, arguments, and environment variable mappings.
Execution Flow
When a user executes the uvicorn command, the following flow occurs:
- Argument Parsing:
clickparses command-line arguments and environment variables (prefixed withUVICORN_). - Configuration Initialization: The
mainfunction callsrun, which instantiates aConfigobject. - Process Management Selection: Based on the
reloadandworkerssettings, Uvicorn decides whether to run a single process server, aChangeReloadsupervisor, or aMultiprocesssupervisor. - Application Loading: The
Configobject imports and loads the ASGI application.
Sources: uvicorn/main.py:461-512, pyproject.toml:98-98
Centralized Configuration (Config class)
The Config class in uvicorn/config.py acts as the single source of truth for the server. It handles logging setup, SSL context creation, socket binding, and application importing.
Key Responsibilities
- Application Loading: Resolves the
appstring (e.g.,"module:app") into a callable usingimport_from_string. - Protocol Selection: Maps "auto" settings to specific protocol implementations like
h11orhttptools. - Logging: Configures the Python logging dictionary based on
LOGGING_CONFIGor external files. - SSL: Creates
ssl.SSLContextobjects if certificates are provided.
Sources: uvicorn/config.py:146-240
Protocol Mapping Tables
The configuration system maps string identifiers to internal implementation classes.
| Setting | Type | Mapping Source |
|---|---|---|
http | HTTPProtocolType | HTTP_PROTOCOLS (h11, httptools) |
ws | WSProtocolType | WS_PROTOCOLS (websockets, wsproto, etc.) |
loop | LoopFactoryType | LOOP_FACTORIES (asyncio, uvloop) |
lifespan | LifespanType | LIFESPAN (on, off, auto) |
Sources: uvicorn/config.py:38-70
Configuration Options
Uvicorn supports a wide array of options via the Config constructor and CLI flags.
| Option | Type | Default | Description |
|---|---|---|---|
app | str | N/A | The ASGI application location (Required). |
host | str | "127.0.0.1" | IP address to bind. |
port | int | 8000 | Port to bind. |
workers | int | 1 | Number of worker processes. |
reload | bool | False | Enable auto-reload on code change. |
log_level | str | "info" | Logging level (critical, error, warning, info, debug, trace). |
proxy_headers | bool | True | Populate remote address via proxy headers. |
ssl_certfile | str | None | Path to SSL certificate. |
Sources: uvicorn/main.py:65-300, uvicorn/config.py:146-210
Application and Interface Discovery
Uvicorn can automatically detect the type of application interface being used (ASGI3, ASGI2, or WSGI).
- Importing: The
load_appmethod usesimport_from_stringto fetch the object. - Detection: If
interfaceis set to "auto", Uvicorn inspects the object:- If the object (or its
__call__method) is a coroutine function, it defaults to asgi3. - Otherwise, it falls back to asgi2.
- If the object (or its
- WSGI Support: If the
interfaceis explicitly set to "wsgi", the application is wrapped inWSGIMiddleware.
Sources: uvicorn/config.py:463-490, uvicorn/importer.py
Socket Binding Logic
The Config.bind_socket() method handles the creation of the server socket based on the provided parameters. It supports three distinct modes:
- UNIX Domain Socket (UDS): Triggered by the
udsparameter. - File Descriptor (FD): Triggered by the
fdparameter. - TCP Socket: The default mode using
hostandport.
# From uvicorn/config.py:518-550
if self.uds is not None:
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
sock.bind(self.uds)
elif self.fd is not None:
sock = socket.fromfd(self.fd, socket.AF_UNIX, socket.SOCK_STREAM)
else:
sock = socket.socket(family=family)
sock.bind((self.host, self.port))
Sources: uvicorn/config.py:518-550
Multi-Process and Reload Logic
Process management is tightly integrated with configuration. The use_subprocess property returns True if either reload is enabled or workers > 1.
Restrictions
- The
appmust be passed as an import string (not an instance) when usingreloadorworkers. - If
reloadis enabled, theworkersflag is ignored and a warning is issued.
Sources: uvicorn/config.py:317-318, uvicorn/main.py:504-508, tests/test_config.py:315-318
Conclusion
The CLI and Configuration module forms the backbone of Uvicorn's flexibility. By centralizing logic in the Config class, Uvicorn ensures consistent behavior whether the server is started programmatically via uvicorn.run() or via the command line. This architecture allows for advanced features like automatic interface detection, complex logging configurations, and seamless integration with process supervisors.