got Future <Future pending> attached to a different loop #6566
-
First Check
Commit to Help
Example Codedef main():
uvicorn.run(app,host="0.0.0.0",port=8090,loop="asyncio")
loop = asyncio.get_event_loop()
def run():
loop.run_until_complete(main())
def keep_alive1():
t = threading.Thread(target=run)
t.start()
keep_alive1()
client.run('discord bot token') Descriptioni was using discord client with fastapi i used another thread for running uvicorn.
the endpoint that gave me this error was asynchronous using mongodb module motor, other non asynchronous endpoints worked fine like the /docs. when i removed the discord client with just the fastapi it still didnt worked with uvicorn.run() but did worked with the cmd command uvicorn main:app not sure why tho. Operating SystemWindows Operating System DetailsNo response FastAPI Version0.66.0 Python Version3.9.4 Additional ContextNo response |
Beta Was this translation helpful? Give feedback.
Replies: 6 comments 1 reply
-
This is a quite common issue when using Motor (unfortunately, their implementation doesn't always play well with some event loops patterns). I wrote some details about this some time ago here: fastapi-users/fastapi-users#663 (reply in thread) When using Motor, if you want to invoke Uvicorn programmatically you have to make sure of two things:
# main.py
import uvicorn
if __name__ == "__main__":
# Assuming your `app` variable is in a module named `app.py`
uvicorn.run("app:app", host="0.0.0.0", port=8000) BTW, I see in your example that you do |
Beta Was this translation helpful? Give feedback.
-
Is this related to encode/uvicorn#1110 ? |
Beta Was this translation helpful? Give feedback.
-
From what I understand of the issue, yes, this is what probably causes the problem. However, I also think that Motor could greatly improve things on their side: contrary to most database drivers, they don't provide a connect/disconnect mechanism we could trigger on FastAPI startup; which would be then in the right loop context. |
Beta Was this translation helpful? Give feedback.
-
Yeah, that PR solves an issue that should never happen. :) |
Beta Was this translation helpful? Give feedback.
-
thanks it worked, tho you should add a little note in the docs about the motor connector. |
Beta Was this translation helpful? Give feedback.
-
The issue could also be creating |
Beta Was this translation helpful? Give feedback.
This is a quite common issue when using Motor (unfortunately, their implementation doesn't always play well with some event loops patterns). I wrote some details about this some time ago here: fastapi-users/fastapi-users#663 (reply in thread)
When using Motor, if you want to invoke Uvicorn programmatically you have to make sure of two things:
main.py
) alone, not besides theapp
instance;app
to pass it to uvicorn: prefer the import path as a string. This way, you'll ensure Uvicorn imports the module by itself with the right loop attached: