`uvicorn.run` event loop behaviour when running programmatically.
See original GitHub issueI am trying to run Uvicorn in the same asyncio loop as some other components like the asyncpg DB connection pool.
As far as I can tell we can specify the callable that receives the scope and creates the request coroutine two ways:
-
Passing a
str
containing the path touvicorn.run
but then we can’t setup our dependencies (db, redis) since that function is called each new request. We could load the dependencies by creating them when the file is imported but there is no way that will pass codereview. -
Pass a callable to
uvicorn.run
with the dependencies in the scope. Unfortunatelyuvicorn
destroy the current event loop and replaces the event loop policy during the setup phase.
What is the recommended way to do things like this? If I could pass a loop instance in the loop
parameter to run
and have uvicorn use that directly without destroying it then it then I could use alternative 2 as long as we don’t call unicorn.run
from a async function due to the server.run
behaviour..
Issue Analytics
- State:
- Created 5 years ago
- Comments:6 (4 by maintainers)
Am I correct in assuming this is no longer supported? As far as I can see,
Config.setup_event_loop
(config.py line 213) now once again unconditionally dereferencesLOOP_SETUPS
with theloop
argument.Pull request was merged and then the behavior was removed i believe in this commit: https://github.com/encode/uvicorn/pull/276
In my case i need to run message-consumers based on aio-pika aside a set HTTP endpoints served by uvicorn in the same event loop in my microservice application.
The only way of doing this i found is to move configuration and initialization of my consumers inside app served by uvicorn.
for example like this(sorry for a shitcode but the way is exactly the same - we’re just not messing around with event loop before uvicorn kiks in):