From c01386b9e020667ad5d6d775d13f00ab00e89a0d Mon Sep 17 00:00:00 2001 From: Marcelo Trylesinski Date: Mon, 20 Jun 2022 22:05:54 +0200 Subject: [PATCH] Document how to run uvicorn programatically (#1525) * Document how to run uvicorn programatically * Apply suggestions from code review Co-authored-by: Florimond Manca * Apply suggestions from code review Co-authored-by: Florimond Manca * Shrink configuration command * Update docs/index.md Co-authored-by: Florimond Manca --- docs/index.md | 43 ++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 40 insertions(+), 3 deletions(-) diff --git a/docs/index.md b/docs/index.md index cae1a2c0ad..3c4cd6532b 100644 --- a/docs/index.md +++ b/docs/index.md @@ -196,9 +196,26 @@ For more information, see the [settings documentation](settings.md). ### Running programmatically -To run uvicorn directly from your application... +There are several ways to run uvicorn directly from your application. -**example.py**: +#### `uvicorn.run` + +If you're looking for a programmatic equivalent of the `uvicorn` command line interface, use `uvicorn.run()`: + +```python +# main.py +import uvicorn + +async def app(scope, receive, send): + ... + +if __name__ == "__main__": + uvicorn.run("main:app", port=5000, log_level="info") +``` + +#### `Config` and `Server` instances + +For more control over configuration and server lifecycle, use `uvicorn.Config` and `uvicorn.Server`: ```python import uvicorn @@ -207,7 +224,27 @@ async def app(scope, receive, send): ... if __name__ == "__main__": - uvicorn.run("example:app", host="127.0.0.1", port=5000, log_level="info") + config = uvicorn.Config("main:app", port=5000, log_level="info") + server = uvicorn.Server(config) + server.run() +``` + +If you'd like to run Uvicorn from an already running async environment, use `uvicorn.Server.serve()` instead: + +```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()) ``` ### Running with Gunicorn