### Install project dependencies Source: https://github.com/kludex/uvicorn/blob/main/docs/contributing.md Install the project and its dependencies after navigating to the repository directory. ```shell $ cd uvicorn $ scripts/install ``` -------------------------------- ### Install and Run rloop Source: https://github.com/kludex/uvicorn/blob/main/docs/concepts/event-loop.md Install the experimental rloop library and configure Uvicorn to use it. ```bash pip install rloop ``` ```bash uv add rloop ``` ```bash uvicorn main:app --loop rloop:new_event_loop ``` -------------------------------- ### Install Uvicorn (uv) Source: https://github.com/kludex/uvicorn/blob/main/docs/installation.md Use this command to install Uvicorn with its minimal dependencies using uv. ```bash uv add uvicorn ``` -------------------------------- ### Install and Run Winloop Source: https://github.com/kludex/uvicorn/blob/main/docs/concepts/event-loop.md Install the Winloop library for Windows performance and configure Uvicorn to use it. ```bash pip install winloop ``` ```bash uv add winloop ``` ```bash uvicorn main:app --loop winloop:new_event_loop ``` -------------------------------- ### Serve documentation locally Source: https://github.com/kludex/uvicorn/blob/main/docs/contributing.md Start a local server to preview documentation changes. ```shell $ scripts/docs serve ``` -------------------------------- ### Install Uvicorn with Standard Dependencies (uv) Source: https://github.com/kludex/uvicorn/blob/main/docs/installation.md Install Uvicorn along with all optional dependencies for full feature support using uv. ```bash uv add 'uvicorn[standard]' ``` -------------------------------- ### Build and run the Docker container Source: https://github.com/kludex/uvicorn/blob/main/docs/deployment/docker.md Commands to build the image and start the container. ```bash docker build -t my-app . docker run -p 8000:8000 my-app ``` -------------------------------- ### Install Uvicorn using uv Source: https://github.com/kludex/uvicorn/blob/main/docs/index.md Install Uvicorn using the 'uv' package manager. This is an alternative installation method. ```bash uv add uvicorn ``` -------------------------------- ### Install Hypercorn ASGI server Source: https://github.com/kludex/uvicorn/blob/main/README.md Install the Hypercorn ASGI server using pip. Hypercorn supports asyncio and trio. ```shell pip install hypercorn ``` -------------------------------- ### Install Uvicorn (pip) Source: https://github.com/kludex/uvicorn/blob/main/docs/installation.md Use this command to install Uvicorn with its minimal dependencies using pip. ```bash pip install uvicorn ``` -------------------------------- ### Install Daphne ASGI server Source: https://github.com/kludex/uvicorn/blob/main/README.md Install the Daphne ASGI server using pip. This is an alternative ASGI server implementation. ```shell pip install daphne ``` -------------------------------- ### Install Uvicorn with Standard Dependencies (pip) Source: https://github.com/kludex/uvicorn/blob/main/docs/installation.md Install Uvicorn along with all optional dependencies for full feature support using pip. ```bash pip install 'uvicorn[standard]' ``` -------------------------------- ### Basic ASGI application example Source: https://github.com/kludex/uvicorn/blob/main/README.md A simple ASGI application that responds with 'Hello, world!' to HTTP requests. Ensure this is saved in a Python file (e.g., example.py). ```python async def app(scope, receive, send): assert scope['type'] == 'http' await send({ 'type': 'http.response.start', 'status': 200, 'headers': [ (b'content-type', b'text/plain'), ], }) await send({ 'type': 'http.response.body', 'body': b'Hello, world!', }) ``` -------------------------------- ### Uvicorn startup output Source: https://github.com/kludex/uvicorn/blob/main/docs/deployment/docker.md Expected console output when starting the Uvicorn server. ```bash INFO: Started server process [62727] INFO: Waiting for application startup. INFO: ASGI 'lifespan' protocol appears unsupported. INFO: Application startup complete. INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) ``` -------------------------------- ### Run the application locally Source: https://github.com/kludex/uvicorn/blob/main/docs/deployment/docker.md Starts the Uvicorn server using the uv run command. ```bash uv run uvicorn main:app ``` -------------------------------- ### Configure Uvicorn with Environment Variables Source: https://github.com/kludex/uvicorn/blob/main/docs/settings.md Use environment variables with the prefix `UVICORN_`. This example sets the host and port, then runs the application. ```bash export UVICORN_HOST="0.0.0.0" export UVICORN_PORT="8000" uvicorn main:app ``` -------------------------------- ### YAML Logging Configuration Source: https://github.com/kludex/uvicorn/blob/main/docs/concepts/logging.md Example of a YAML-based logging configuration file. ```yaml version: 1 disable_existing_loggers: false formatters: default: "()": uvicorn.logging.DefaultFormatter fmt: "%(asctime)s - %(levelprefix)s %(message)s" datefmt: "%Y-%m-%d %H:%M:%S" use_colors: null access: "()": uvicorn.logging.AccessFormatter fmt: '%(asctime)s - %(levelprefix)s %(client_addr)s - "%(request_line)s" %(status_code)s' datefmt: "%Y-%m-%d %H:%M:%S" handlers: default: formatter: default class: logging.StreamHandler stream: ext://sys.stderr access: formatter: access class: logging.StreamHandler stream: ext://sys.stdout loggers: uvicorn: handlers: - default level: INFO propagate: false uvicorn.error: level: INFO uvicorn.access: handlers: - access level: INFO propagate: false ``` -------------------------------- ### Run Hypercorn ASGI Server Source: https://github.com/kludex/uvicorn/blob/main/docs/concepts/asgi.md Install and execute the Hypercorn server to run an ASGI application. ```shell pip install hypercorn hypercorn app:App ``` -------------------------------- ### Install Uvicorn using pip Source: https://github.com/kludex/uvicorn/blob/main/docs/index.md Install Uvicorn using pip. This is the standard method for adding the package to your Python environment. ```bash pip install uvicorn ``` -------------------------------- ### JSON Logging Configuration Source: https://github.com/kludex/uvicorn/blob/main/docs/concepts/logging.md Example of a JSON-based logging configuration file. ```json { "version": 1, "disable_existing_loggers": false, "formatters": { "default": { "()": "uvicorn.logging.DefaultFormatter", "fmt": "%(asctime)s - %(levelprefix)s %(message)s", "datefmt": "%Y-%m-%d %H:%M:%S", "use_colors": null }, "access": { "()": "uvicorn.logging.AccessFormatter", "fmt": "%(asctime)s - %(levelprefix)s %(client_addr)s - \"%(request_line)s\" %(status_code)s", "datefmt": "%Y-%m-%d %H:%M:%S" } }, "handlers": { "default": { "formatter": "default", "class": "logging.StreamHandler", "stream": "ext://sys.stderr" }, "access": { "formatter": "access", "class": "logging.StreamHandler", "stream": "ext://sys.stdout" } }, "loggers": { "uvicorn": { "handlers": ["default"], "level": "INFO", "propagate": false }, "uvicorn.error": { "level": "INFO" }, "uvicorn.access": { "handlers": ["access"], "level": "INFO", "propagate": false } } } ``` -------------------------------- ### Run Uvicorn server Source: https://github.com/kludex/uvicorn/blob/main/README.md Execute this command in your terminal to run the ASGI application defined in 'example.py'. The 'app:app' refers to the 'app' callable within the 'example' module. ```shell uvicorn example:app ``` -------------------------------- ### Run Daphne ASGI Server Source: https://github.com/kludex/uvicorn/blob/main/docs/concepts/asgi.md Install and execute the Daphne server to run an ASGI application. ```shell pip install daphne daphne app:App ``` -------------------------------- ### Install Uvicorn Worker Source: https://github.com/kludex/uvicorn/blob/main/docs/index.md Install the uvicorn-worker package for use with Gunicorn. This is recommended for production deployments. ```bash python -m pip install uvicorn-worker ``` -------------------------------- ### Create a cache-aware Dockerfile Source: https://github.com/kludex/uvicorn/blob/main/docs/deployment/docker.md Optimizes build times by installing dependencies before copying project files. ```dockerfile FROM python:3.12-slim COPY --from=ghcr.io/astral-sh/uv:latest /uv /uvx /bin/ # Change the working directory to the `app` directory WORKDIR /app # Install dependencies RUN --mount=type=cache,target=/root/.cache/uv \ --mount=type=bind,source=uv.lock,target=uv.lock \ --mount=type=bind,source=pyproject.toml,target=pyproject.toml \ uv sync --frozen --no-install-project # Copy the project into the image ADD . /app # Sync the project RUN --mount=type=cache,target=/root/.cache/uv \ uv sync --frozen # Run with uvicorn CMD ["uv", "run", "uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"] ``` -------------------------------- ### Basic ASGI Application Source: https://github.com/kludex/uvicorn/blob/main/docs/index.md A minimal ASGI application that responds with 'Hello, world!'. This serves as a basic example for running with Uvicorn. ```python async def app(scope, receive, send): assert scope['type'] == 'http' await send({ 'type': 'http.response.start', 'status': 200, 'headers': [ (b'content-type', b'text/plain'), (b'content-length', b'13'), ], }) await send({ 'type': 'http.response.body', 'body': b'Hello, world!', }) ``` -------------------------------- ### Run Uvicorn with Command Line Options Source: https://github.com/kludex/uvicorn/blob/main/docs/settings.md Use command line options when running Uvicorn directly. This example binds to all interfaces on port 8000. ```bash uvicorn main:app --host 0.0.0.0 --port 8000 ``` -------------------------------- ### Example HTTP Connection Scope Source: https://github.com/kludex/uvicorn/blob/main/docs/concepts/asgi.md A sample dictionary structure representing the connection scope for an incoming HTTP request. ```python { 'type': 'http', 'scheme': 'http', 'root_path': '', 'server': ('127.0.0.1', 8000), 'http_version': '1.1', 'method': 'GET', 'path': '/', 'headers': [ (b'host', b'127.0.0.1:8000'), (b'user-agent', b'curl/7.51.0'), (b'accept', b'*/*') ] } ``` -------------------------------- ### Run Gunicorn with Uvicorn Workers Source: https://github.com/kludex/uvicorn/blob/main/docs/deployment/index.md Deploy Uvicorn in production using Gunicorn as a process manager. This is a common and recommended setup. ```bash gunicorn -w 4 -k uvicorn.workers.UvicornWorker ``` -------------------------------- ### Initialize a new project with uv Source: https://github.com/kludex/uvicorn/blob/main/docs/deployment/docker.md Creates a new project structure using the uv package manager. ```bash uv init app ``` -------------------------------- ### Serve Uvicorn from an async environment Source: https://github.com/kludex/uvicorn/blob/main/docs/index.md Serve Uvicorn from an already running async environment using `uvicorn.Server.serve()`. This is useful for integrating Uvicorn into existing async applications. ```python import asyncio import uvicorn async def app(scope, receive, send): ... async def main(): config = uvicorn.Config("main:app", port=5000, log_level="info") server = uvicorn.Server(config) await server.serve() if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Project directory structure Source: https://github.com/kludex/uvicorn/blob/main/docs/deployment/docker.md The default file layout generated by uv init. ```bash app/ ├── main.py ├── pyproject.toml └── README.md ``` -------------------------------- ### Create a simple ASGI application Source: https://github.com/kludex/uvicorn/blob/main/docs/deployment/docker.md A basic ASGI-compliant application for testing Uvicorn. ```python async def app(scope, receive, send): body = "Hello, world!" await send( { "type": "http.response.start", "status": 200, "headers": [ [b"content-type", b"text/plain"], [b"content-length", len(body)], ], } ) await send( { "type": "http.response.body", "body": body.encode("utf-8"), } ) ``` -------------------------------- ### Send HTTP Response Messages Source: https://github.com/kludex/uvicorn/blob/main/docs/concepts/asgi.md Communicate with the server by sending start and body messages to the send coroutine. ```python await send({ 'type': 'http.response.start', 'status': 200, 'headers': [ [b'content-type', b'text/plain'], ] }) await send({ 'type': 'http.response.body', 'body': b'Hello, world!', }) ``` -------------------------------- ### Run Uvicorn from command line Source: https://github.com/kludex/uvicorn/blob/main/docs/index.md Run the Uvicorn server from the command line, serving the specified ASGI application. ```shell uvicorn main:app ``` -------------------------------- ### Run Uvicorn programmatically with Config and Server Source: https://github.com/kludex/uvicorn/blob/main/docs/index.md Use `uvicorn.Config` and `uvicorn.Server` for more control over server configuration and lifecycle when running Uvicorn programmatically. ```python import uvicorn async def app(scope, receive, send): ... if __name__ == "__main__": config = uvicorn.Config("main:app", port=5000, log_level="info") server = uvicorn.Server(config) server.run() ``` -------------------------------- ### Run Uvicorn Programmatically (Direct App Instance) Source: https://github.com/kludex/uvicorn/blob/main/docs/deployment/index.md Pass the application instance directly to `uvicorn.run`. This method has limitations and is not recommended if using multiprocessing or reloading. ```python uvicorn.run(app, host="127.0.0.1", port=5000, log_level="info") ``` -------------------------------- ### Clone the Uvicorn repository Source: https://github.com/kludex/uvicorn/blob/main/docs/contributing.md Initial step to set up a local development environment by cloning a fork of the repository. ```shell $ git clone https://github.com/YOUR-USERNAME/uvicorn ``` -------------------------------- ### Apply Custom Logging Configuration Source: https://github.com/kludex/uvicorn/blob/main/docs/concepts/logging.md Methods to apply a custom logging configuration file via CLI or programmatically. ```bash uvicorn main:app --log-config log_config.yaml ``` ```python uvicorn.run("main:app", log_config="log_config.yaml") ``` -------------------------------- ### Run Uvicorn programmatically with uvicorn.run Source: https://github.com/kludex/uvicorn/blob/main/docs/index.md Programmatically run Uvicorn using the `uvicorn.run()` function, which mirrors the command-line interface. Specify the application and port. ```python import uvicorn async def app(scope, receive, send): ... if __name__ == "__main__": uvicorn.run("main:app", port=5000, log_level="info") ``` -------------------------------- ### Run Uvicorn with Application Factory Source: https://github.com/kludex/uvicorn/blob/main/docs/index.md Load an ASGI application using the --factory flag with Uvicorn. The factory function is specified in the format 'module:factory_function'. ```shell uvicorn --factory main:create_app ``` -------------------------------- ### Supervisor Configuration for Uvicorn Source: https://github.com/kludex/uvicorn/blob/main/docs/deployment/index.md A basic supervisor configuration to manage multiple Uvicorn processes using file descriptor passing. ```ini [supervisord] [fcgi-program:uvicorn] socket=tcp://localhost:8000 command=venv/bin/uvicorn --fd 0 main:App numprocs=4 process_name=uvicorn-%(process_num)d stdout_logfile=/dev/stdout stdout_logfile_maxbytes=0 ``` -------------------------------- ### Use Custom Event Loop Source: https://github.com/kludex/uvicorn/blob/main/docs/concepts/event-loop.md Specify a custom event loop implementation using module path and function name. ```bash uvicorn main:app --loop : ``` -------------------------------- ### Run Daphne ASGI server Source: https://github.com/kludex/uvicorn/blob/main/README.md Command to run an ASGI application using the Daphne server. Replace 'app:App' with your application's module and callable. ```shell daphne app:App ``` -------------------------------- ### Use a standard logging formatter Source: https://github.com/kludex/uvicorn/blob/main/docs/concepts/logging.md Use the standard logging.Formatter if colorized output is not required. Note that access log specific placeholders are unavailable with this formatter. ```yaml version: 1 disable_existing_loggers: false formatters: default: format: "%(asctime)s [%(levelname)s] %(name)s: %(message)s" datefmt: "%Y-%m-%d %H:%M:%S" handlers: default: formatter: default class: logging.StreamHandler stream: ext://sys.stderr loggers: uvicorn: handlers: - default level: INFO propagate: false uvicorn.error: level: INFO uvicorn.access: handlers: - default level: INFO propagate: false ``` -------------------------------- ### Run Uvicorn with Gunicorn Source: https://github.com/kludex/uvicorn/blob/main/docs/index.md Run an ASGI application using Gunicorn with the Uvicorn worker class. This provides Uvicorn's performance benefits with Gunicorn's process management. ```bash gunicorn example:app -w 4 -k uvicorn.workers.UvicornWorker ``` -------------------------------- ### Run Hypercorn ASGI server Source: https://github.com/kludex/uvicorn/blob/main/README.md Command to run an ASGI application using the Hypercorn server. Replace 'app:App' with your application's module and callable. ```shell hypercorn app:App ``` -------------------------------- ### Configure Docker Compose for development Source: https://github.com/kludex/uvicorn/blob/main/docs/deployment/docker.md Enables hot-reloading and volume mounting for local development. ```yaml services: backend: build: . ports: - "8000:8000" environment: - UVICORN_RELOAD=true volumes: - .:/app tty: true ``` -------------------------------- ### Run Uvicorn with Reloading Source: https://github.com/kludex/uvicorn/blob/main/docs/deployment/index.md Use this command for local development to enable auto-reloading when code changes. ```bash $ uvicorn main:app --reload --port 5000 ``` -------------------------------- ### Run Uvicorn with HTTPS Source: https://github.com/kludex/uvicorn/blob/main/docs/deployment/index.md Command to run Uvicorn with HTTPS enabled, requiring certificate and key files. ```bash uvicorn main:app --port 5000 --ssl-keyfile=./key.pem --ssl-certfile=./cert.pem ``` -------------------------------- ### Echo Request Method and Path Source: https://github.com/kludex/uvicorn/blob/main/docs/concepts/asgi.md A basic application that reads the request scope and returns the method and path in the response body. ```python async def app(scope, receive, send): """ Echo the method and path back in an HTTP response. """ assert scope['type'] == 'http' body = f'Received {scope["method"]} request to {scope["path"]}' await send({ 'type': 'http.response.start', 'status': 200, 'headers': [ [b'content-type', b'text/plain'], ] }) await send({ 'type': 'http.response.body', 'body': body.encode('utf-8'), }) ``` -------------------------------- ### Define ASGI Application Patterns Source: https://github.com/kludex/uvicorn/blob/main/docs/concepts/asgi.md Implement an ASGI application using either a function-based or instance-based approach. Both patterns require an async callable accepting scope, receive, and send arguments. ```python async def app(scope, receive, send): assert scope['type'] == 'http' ... ``` ```python class App: async def __call__(self, scope, receive, send): assert scope['type'] == 'http' ... app = App() ``` -------------------------------- ### Include Files for Reloading Source: https://github.com/kludex/uvicorn/blob/main/docs/settings.md Use `--reload-include` with a glob pattern to specify which files or directories should be watched for changes when using watchfiles. ```bash uvicorn main:app --reload --reload-include '*.py' ``` -------------------------------- ### Configure Uvicorn Event Loop Source: https://github.com/kludex/uvicorn/blob/main/docs/concepts/event-loop.md Specify the event loop implementation using the --loop flag. ```bash uvicorn main:app --loop ``` -------------------------------- ### Implement ASGI application with lifespan Source: https://github.com/kludex/uvicorn/blob/main/docs/concepts/lifespan.md A minimal ASGI application handling both lifespan events and HTTP requests. The lifespan logic is executed once per application instance. ```python async def app(scope, receive, send): if scope['type'] == 'lifespan': while True: message = await receive() if message['type'] == 'lifespan.startup': print("Application is starting up...") await send({'type': 'lifespan.startup.complete'}) elif message['type'] == 'lifespan.shutdown': print("Application is shutting down...") await send({'type': 'lifespan.shutdown.complete'}) return elif scope['type'] == 'http': await send({ 'type': 'http.response.start', 'status': 200, 'headers': [(b'content-type', b'text/plain')], }) await send({'type': 'http.response.body', 'body': b'Hello, World!'}) else: raise RuntimeError("This server doesn't support WebSocket.") ``` -------------------------------- ### Define Application Factory Source: https://github.com/kludex/uvicorn/blob/main/docs/index.md Define a factory function that returns an ASGI application. This is used with the --factory flag. ```python def create_app(): app = ... return app ``` -------------------------------- ### Run Uvicorn Programmatically Source: https://github.com/kludex/uvicorn/blob/main/docs/settings.md Use keyword arguments when running programmatically with `uvicorn.run()`. Ensure `uvicorn.run` is within an `if __name__ == '__main__'` block when using `reload=True` or `workers=NUM`. ```python uvicorn.run("main:app", host="0.0.0.0", port=8000) ``` -------------------------------- ### Configure logging programmatically with dictConfig Source: https://github.com/kludex/uvicorn/blob/main/docs/concepts/logging.md Pass a dictionary to the log_config parameter when running Uvicorn programmatically. ```python import uvicorn log_config = { "version": 1, "disable_existing_loggers": False, "formatters": { "default": { "()": "uvicorn.logging.DefaultFormatter", "fmt": "%(asctime)s - %(levelprefix)s %(message)s", "datefmt": "%Y-%m-%d %H:%M:%S", }, "access": { "()": "uvicorn.logging.AccessFormatter", "fmt": '%(asctime)s - %(levelprefix)s %(client_addr)s - "%(request_line)s" %(status_code)s', "datefmt": "%Y-%m-%d %H:%M:%S", }, }, "handlers": { "default": { "formatter": "default", "class": "logging.StreamHandler", "stream": "ext://sys.stderr", }, "access": { "formatter": "access", "class": "logging.StreamHandler", "stream": "ext://sys.stdout", }, }, "loggers": { "uvicorn": {"handlers": ["default"], "level": "INFO", "propagate": False}, "uvicorn.error": {"level": "INFO"}, "uvicorn.access": {"handlers": ["access"], "level": "INFO", "propagate": False}, }, } uvicorn.run("main:app", log_config=log_config) ``` -------------------------------- ### Run linting and code checks Source: https://github.com/kludex/uvicorn/blob/main/docs/contributing.md Commands to perform auto-formatting and static code analysis. ```shell $ scripts/lint ``` ```shell $ scripts/check ``` -------------------------------- ### Run Gunicorn Worker with Uvicorn and HTTPS Source: https://github.com/kludex/uvicorn/blob/main/docs/deployment/index.md Command to run Gunicorn with Uvicorn worker, enabling HTTPS using certificate and key files. ```bash gunicorn --keyfile=./key.pem --certfile=./cert.pem -k uvicorn.workers.UvicornWorker main:app ``` -------------------------------- ### Default Logging Configuration Source: https://github.com/kludex/uvicorn/blob/main/docs/concepts/logging.md The default dictionary configuration applied by Uvicorn for logging. ```python LOGGING_CONFIG = { "version": 1, "disable_existing_loggers": False, "formatters": { "default": { "()": "uvicorn.logging.DefaultFormatter", "fmt": "%(levelprefix)s %(message)s", "use_colors": None, }, "access": { "()": "uvicorn.logging.AccessFormatter", "fmt": '%(levelprefix)s %(client_addr)s - "%(request_line)s" %(status_code)s', }, }, "handlers": { "default": { "formatter": "default", "class": "logging.StreamHandler", "stream": "ext://sys.stderr", }, "access": { "formatter": "access", "class": "logging.StreamHandler", "stream": "ext://sys.stdout", }, }, "loggers": { "uvicorn": {"handlers": ["default"], "level": "INFO", "propagate": False}, "uvicorn.error": {"level": "INFO"}, "uvicorn.access": {"handlers": ["access"], "level": "INFO", "propagate": False}, }, } ``` -------------------------------- ### Run Gunicorn with Uvicorn H11 Workers Source: https://github.com/kludex/uvicorn/blob/main/docs/deployment/index.md Use the `UvicornH11Worker` for PyPy or when a pure-Python implementation is preferred over `uvloop` and `httptools`. ```bash gunicorn -w 4 -k uvicorn.workers.UvicornH11Worker ``` -------------------------------- ### Run project tests Source: https://github.com/kludex/uvicorn/blob/main/docs/contributing.md Execute the test suite using the provided script. Additional arguments are passed directly to pytest. ```shell $ scripts/test ``` ```shell $ scripts/test tests/test_cli.py ```