5

Use pool connection - aiomysql

my code looks like this:

# POOL CONNECTION

# create pool connection
async def create_pool():
    print("Creating pool connection...")
    global pool

    pool = await aiomysql.create_pool(
        host=DB_HOST,
        port=DB_PORT,
        user=DB_USER,
        password=DB_PASSWORD,
        db=DB_DBNAME,
        autocommit=True
    )


async def get_connection():
    async with pool.acquire() as conn:
        return conn
    pool.close()
    await pool.wait_closed()


connection = await get_connection()
async with connection.cursor() as cursor:
            await cursor.execute(...)

If a single request is made, which makes the connection to mysql, it runs correctly, but if 2 or more requests are made at the same time, this crashes and thrown this error:

readexactly() called while another coroutine is already waiting for incoming data

timmy
  • 65
  • 5
  • What is the URL for the python code (example or tutorial) you used as a base for your solution? There may be more details to consider for multi simultaneous user management. – Wilson Hauck Dec 25 '21 at 15:14
  • 1
    You are using a return inside `get_connection`, this will kill the `async with` ctx manager, hence conn might already been invalid when you return it. (not sure tho), but if you use a ctx manager inside a function you have to `yield` it from the function and later call the function again to teardown the context. If you `yield` your function becomes a generator so when you call the function you will get a generator object. And on that you then have to call `anext` (next iterator from generator) which will yield you conn for the first time. Then again `anext` to tear it down. – Dimfred Oct 30 '22 at 16:40

0 Answers0