1

Python 3.8, aiomysql

I have a code:

import aiomysql

class AsyncSQL:
    def __init__(self, loop):
        self.pool = aiomysql.create_pool(host="localhost", user="root", password="root",
                                              db="chatdb", charset="utf8", loop=loop)

    async def select_query(self, query):
        async with self.pool.acquire() as con: # HERE ERROR APPEARS
            async with con.cursor() as cur:
                await cur.execute(query)
                rows = await cur.fetchall()
                desc = await cur.description()
                await cur.close()
                return rows, desc

    async def insert_query(self, query):
        async with self.pool.acquire() as con:  # HERE ERROR APPEARS
            async with con.cursor() as cur:
                await cur.execute(query)
                await con.commit()
                await cur.close()

    async def update_query(self, query):
        async with self.pool.acquire() as con:  # HERE ERROR APPEARS
            async with con.cursor() as cur:
                await cur.execute(query)
                await con.commit()
                rows = await cur.fetchall()
                desc = await cur.description()
                await cur.close()
                return rows, desc

    def close_connection(self):
        self.pool.close()

But, instead of working, I have an runtime error

async with self.pool.acquire() as con:
AttributeError: '_PoolContextManager' object has no attribute 'acquire'

For some reason, aiomysql.create_pool() returns _PoolContextManager and not Pool instance.

Same thing with aiomysql.connect() - it returns _ConnectionContextManager, instead of Connection

What I should do to get instance from creat_pool() or connect() or how I should deal with ContextManager. Maby, i do something completely wrong.

np2314
  • 645
  • 5
  • 14
MhDelt
  • 21
  • 3
  • Try `with (yield from pool) as con:` as shown in [pool docs](https://aiomysql.readthedocs.io/en/latest/pool.html#Pool). – Glenn Gribble Dec 29 '20 at 07:14
  • It solved `AttributeError`, but now it raise `OperationalError(2003, pymysql.err.OperationalError: (2003, "Can't connect to MySQL server on 'localhost'")`. But I can connect through commadline and MySQL Workbench with same parameters – MhDelt Dec 29 '20 at 13:24
  • MySQLdb can connect to database with this parameters too – MhDelt Dec 29 '20 at 14:20
  • Try a much simpler example to debug that, such as the [example in docs for connect](https://aiomysql.readthedocs.io/en/latest/connection.html#connection). If that still doesn't work, you might want to post a new question with that specific issue. – Glenn Gribble Dec 29 '20 at 18:00
  • Maybe [this answer](https://stackoverflow.com/questions/60879121/aiomysql-not-connecting-with-python) would help. – Glenn Gribble Dec 29 '20 at 18:06

0 Answers0