Uvicorn
lastmod 2023-03-17created 2022-10-073 edits
Running programmatically
There are several ways to run uvicorn directly from your application.
uvicorn.run
If you are looking for a programmatic equivalent of the uvicorn command line interface, use uvicorn.run().
# 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 the server lifecycle, use uvicorn.Config and uvicorn.Server.
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()
To run Uvicorn from an already running asynchronous environment, use uvicorn.Server.serve() instead.
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())
See also
Favorite site
Pages that link here