pythonpython-asyncioaiohttpaio-mysql

Do I need to keep track of the asyncio event loop, or can I just call asyncio.get_event_loop when it is needed?


I am writing a REST API using aiohttp.

Some of the coroutines need to call the database using the aiomysql library. The documentation for aiomysql has the following example:

import asyncio
import aiomysql

loop = asyncio.get_event_loop()


async def test_example():
    conn = await aiomysql.connect(host='127.0.0.1', port=3306,
                                       user='root', password='', db='mysql',
                                       loop=loop)

    cur = await conn.cursor()
    await cur.execute("SELECT Host,User FROM user")
    print(cur.description)
    r = await cur.fetchall()
    print(r)
    await cur.close()
    conn.close()

loop.run_until_complete(test_example())

My question is concerning the definition of the global variable loop:

loop = asyncio.get_event_loop()

Do I really need to keep loop as a global variable somewhere, or can I just call asyncio.get_event_loop() when I need it?

For example, it the code example above, I could get the event loop when I am connecting to the database:

    conn = await aiomysql.connect(host='127.0.0.1', port=3306,
                                       user='root', password='', db='mysql',
                                       loop=asyncio.get_event_loop())

Is there a non-trivial runtime cost to calling asyncio.get_event_loop() or something else that I am missing?


Solution

  • loop argument should go.

    aiomysql should be updated to don't accept the loop.

    You can just skip loop=... in your code right now because aiomysql.connect() has the default loop=None value for the argument.

    In general, asyncio.get_event_loop() will be deprecated; asyncio.get_running_loop() is recommended for the usage from an async code when needed. Passing an explicit loop to asyncio API is deprecated starting from Python 3.8.