getting task attached to a different loop runtime error when using fastapi with gunicron and motor
See original GitHub issueFirst Check
- I added a very descriptive title to this issue.
- I used the GitHub search to find a similar issue and didn’t find it.
- I searched the FastAPI documentation, with the integrated search.
- I already searched in Google “How to X in FastAPI” and didn’t find any information.
- I already read and followed all the tutorial in the docs and didn’t find an answer.
- I already checked if it is not related to FastAPI but to Pydantic.
- I already checked if it is not related to FastAPI but to Swagger UI.
- I already checked if it is not related to FastAPI but to ReDoc.
Commit to Help
- I commit to help with one of those options 👆
Example Code
# mongo
from motor import motor_asyncio
mongo_uri = "mongodb://mongoUser:***/?authSource=admin"
mongo_client = motor_asyncio.AsyncIOMotorClient(mongo_uri)
def get_users_db() -> motor_asyncio.AsyncIOMotorDatabase:
return mongo_client.devdb
# user_routes
import fastapi
import mongo
from bson import objectid
db = mongo.get_users_db()
router = fastapi.APIRouter()
@router.get("/{user_id}")
async def get_user_by_id(user_id: str):
user = await db.users.find_one({"_id": objectid.ObjectId(user_id)})
if user:
user["_id"] = str(user["_id"])
return user
return {"error": "no user found"}
# main.py
import fastapi
import user_routes
app = fastapi.FastAPI()
app.include_router(user_routes.router)
Description
i am trying to create an app with mongodb client motor
and fastapi
. I created seperate routes and a seperate file to setup mongodb client. Running this with uvicorn
works fine and i get results after querying the database but when i deploy the app with gunicorn
and again use the route, i get the following error.
I tried bunch of methods, like assigning a loop to motor client, changing uvworker to use asyncio loop etc. i don’t know where to post this error but here i am
- expected: json of user with given id from database or no user found error
- got: Runtime error
Operating System
Linux
Operating System Details
Debian 11
FastAPI Version
0.68.1
Python Version
Python 3.9.2
Additional Context
motor==2.2.6 gunicorn==20.1
this issue only happens with gunicorn as server and only when accessing mongodb from a fastapi route (i checked running db query in the mongo file and it works)
this my first ever time creating an issue, so please guide me i did something wrong.
Issue Analytics
- State:
- Created 2 years ago
- Reactions:2
- Comments:10 (3 by maintainers)
Top GitHub Comments
That is the problem: https://github.com/encode/starlette/issues/1315
works for me
you should define in start up , like this :
now you can use mongo client every where you want!!!