Running Uvicorn from inside a running loop #2457
-
I'm developing an API using FastAPI and Uvicorn as the server runner. Initially my plan is to use a class wrapper around FastAPI and call uvicorn from there. The entire app is designed to be asynchronous. Line 65 in 47304d9 instead of the entry point Line 589 in 47304d9 Is this done by design or for convenience? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 2 replies
-
The use of asyncio.run() inside the server.run() method in Uvicorn is likely a deliberate decision to simplify cases where the application is entirely asynchronous and doesn't require manual event loop management. The asyncio.run() function starts a new event loop, runs the coroutine, and closes the loop after the execution is complete. This simplifies the task for standard Uvicorn use cases. However, if your code is already running inside an existing event loop, this can cause the "Event loop is already running" error. The main goal of this approach is to make Uvicorn usage easier for most users. However, in advanced scenarios, such as when you are already managing the event loop manually or in complex asynchronous systems, you should avoid calling asyncio.run() and work directly with the existing event loops. |
Beta Was this translation helpful? Give feedback.
https://www.uvicorn.org/#config-and-server-instances