3

I have created a webapp with Quart using MongoDB and using Motor.Asyncio. When the app attempts to query the DB an error is thrown:

Task <Task pending coro=<ASGIHTTPConnection.handle_request() 
running at /home/user/.local/lib/python3.7/site-packages/quart
/asgi.py:59> cb=[_wait.<locals>._on_completion() at /usr/lib/python3.7
/asyncio/tasks.py:440]> got Future <Future pending cb=[run_on_executor.
<locals>._call_check_cancel() at /home/user/.local/lib/python3.7/site-
packages/motor/frameworks/asyncio/__init__.py:80]> attached to a 
different loop

I don't understand why this is occurring or have no idea how solve it.

The app had been running without issue, but I decided to upgrade from Python 3.6 (on Ubuntu-18.04) to python 3.7.1. With this I upgraded Quart to 0.9.0. As a result of this upgrade the above error occurred.

The app run from the command line with Hypercorn and Nginx.

I'm not sure what portions of my code are relevant is this case

I import Quart first then Motor:

    # Mongodb / Gridfs with Motor
    import motor.motor_asyncio
    from pymongo import ReturnDocument
    from bson.objectid import ObjectId
    from bson.son import SON

    client = motor.motor_asyncio.AsyncIOMotorClient()
    db = client.myDataBase
    fs = motor.motor_asyncio.AsyncIOMotorGridFSBucket(db)

After this I add:

    app = Quart(__name__)

I have tried moving this before the motor import block it has changed nothing.

As suggested in the question/answer: RuntimeError: Task attached to a different loop I added:

    loop=asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    client = motor.motor_asyncio.AsyncIOMotorClient(io_loop=loop)

That did not solve it.

This is the block were the first call to motor is made, and where the error occurs:

    try:
        session_info = await db.sessions.find_one(
            {
                'session_id': uuid.UUID(session_id)
            },
            {
                'username':True,
                '_id':False
            }
        )
    except Exception as e:
        print('error retrieving session info:', e)

I can ignore the error and proceed, but then the next call is made and same error occurs.

I understand that Quart works on the default event_loop and there should be no need to create a special loop for motor. It work without out it in the previous version. So I am at complete loss.

2 Answers 2

4

I found the solution, basing myself off of this question: asyncio.run fails when loop.run_until_complete works

The answer provided there suggests moving the initialization of the mongoDB to inside main(). In this specific case, because this a Quart app, there is no main per-se. But the intuition remains.

I defined an initialization function at the module level, then before a call is made to the db I check to see if it is already initialized, if not I call the initialize function.

    import motor.motor_asyncio
    from pymongo import ReturnDocument
    from bson.objectid import ObjectId
    from bson.son import SON

    client = None
    db = None
    fs = None

    async def connect_to_mongo():
        global client, db, fs
        client = motor.motor_asyncio.AsyncIOMotorClient()
        db = client.myDataBase
        fs = motor.motor_asyncio.AsyncIOMotorGridFSBucket(db)

then before a call to the database is made:

    if db is None:
        await connect_to_mongo()

This solved my problem. Why did my code work before the upgrade? I don't know.

2

I know its late reply, but if it helps someone else too;

You can use Quart-Motor (pip install quart-motor) and use it anywhere in your app.

https://github.com/marirs/quart-motor/

from quart_motor import Motor

app = Quart(__name__)
mongo = Motor(app,  uri='...')

@app.route('/<user_name:str>')
async def user_info(user_name):
    user = await mongo.db.users.find_one_or_404({"username": user_name})
    return render_template("user.html", user=user)

Note: I'm the developer of Quart-Motor

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.