Chegevara_kyc
@Chegevara_kyc

Как использовать aiomysql?

Решил перенести скрипт с pymysql на aiomysql, раньше работал так:
модуль с классом Database в котором функции для доступа к бд

С aiomysql решил реализовать также
класс Database
class Database:
    """класс для бд на mysql"""
    @classmethod
    async def connection_to_db(cls,host,user,password,db_name):
        self = cls() 
        self.pool = await aiomysql.create_pool(
            host=host, 
            port=3306,
            user=user, 
            password=password,
            db=db_name)
        self.conn = await self.pool.acquire()
        return self
    async def select_user(self,user_id):
        async with self.conn.cursor() as c:
            await c.execute("SELECT level FROM admins WHERE user_id = user_id;")
            row = await c.fetchall()
            return row[0][0]
#=================BAN==========================================================
    async def add_banned(self,user_id="0000000"):
            async with self.conn.cursor() as c:
                #user_id = user_id
                await c.execute(f"INSERT INTO banned (user_id) VALUES (%s)", user_id)
                await self.conn.commit()
    async def del_banned(self,user_id):
            async with self.conn.cursor() as c:
                await c.execute("DELETE FROM banned WHERE user_id = %s",user_id)
                await self.conn.commit()
#==============================================================================
#=================ADMIN========================================================
    async def get_admins(self,):
        async with self.conn.cursor() as c:
            await c.execute("SELECT user_id FROM admins;")
            rows = await c.fetchall()
            lst = []
            for row in rows:
                lst.append(row[0])
            return lst
            await self.conn.commit()
#==============================================================================
#
#=================BASIC_USER===================================================
    async def user_exists(self,user_id):
        async with self.conn.cursor() as c:
            await c.execute("SELECT * FROM users WHERE user_id =%s", user_id)
            row = await c.fetchall()
           # print(row)
            if row != ():
                return True
            else:
                return False
            await self.conn.commit()
    async def add_user(self,user_id,data=datetime.datetime.today()):
        async with self.conn.cursor() as c:
            #user_id = user_id
            await c.execute(f"INSERT INTO users (user_id,reg_data) VALUES (%s,%s)", user_id,data)
            await self.conn.commit()
#==============================================================================

Потом инициализипровал его:
async def my_sql_main():
    r1 = {
        "host": config.HOST,
        "user": config.USER,
        "password": config.PASSWORD,
        "db_name": config.DB_NAME,
    }
    db = await Database.connection_to_db(**r1)
    return db
db = asyncio.run(my_sql_main())
async def h1():
    await db.get_admins()
asyncio.run(h1())

Но при использовании выдаёт ошибку:
Ошибка

Traceback (most recent call last):
File "e:\_pjq\py\__TG_BOT_0.1(AIOGRAM+MYSQL)\loader.py", line 33, in
asyncio.run(h1())
File "C:\Users\bujhm\AppData\Local\Programs\Python\Python39\lib\asyncio\runners.py", line 44, in run
return loop.run_until_complete(main)
File "C:\Users\bujhm\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 642, in run_until_complete
return future.result()
File "e:\_pjq\py\__TG_BOT_0.1(AIOGRAM+MYSQL)\loader.py", line 32, in h1
await db.get_admins()
File "e:\_pjq\py\__TG_BOT_0.1(AIOGRAM+MYSQL)\Mysql\Mysql_base.py", line 36, in get_admins
await c.execute("SELECT user_id FROM admins;")
File "C:\Users\bujhm\AppData\Local\Programs\Python\Python39\lib\site-packages\aiomysql\cursors.py", line 239, in execute
await self._query(query)
File "C:\Users\bujhm\AppData\Local\Programs\Python\Python39\lib\site-packages\aiomysql\cursors.py", line 457, in _query
await conn.query(q)
File "C:\Users\bujhm\AppData\Local\Programs\Python\Python39\lib\site-packages\aiomysql\connection.py", line 468, in query
await self._execute_command(COMMAND.COM_QUERY, sql)
File "C:\Users\bujhm\AppData\Local\Programs\Python\Python39\lib\site-packages\aiomysql\connection.py", line 713, in _execute_command
self._write_bytes(prelude + sql[:chunk_size - 1])
File "C:\Users\bujhm\AppData\Local\Programs\Python\Python39\lib\site-packages\aiomysql\connection.py", line 658, in _write_bytes return self._writer.write(data)
File "C:\Users\bujhm\AppData\Local\Programs\Python\Python39\lib\asyncio\streams.py", line 341, in write
self._transport.write(data)
File "C:\Users\bujhm\AppData\Local\Programs\Python\Python39\lib\asyncio\proactor_events.py", line 359, in write
self._loop_writing(data=bytes(data))
File "C:\Users\bujhm\AppData\Local\Programs\Python\Python39\lib\asyncio\proactor_events.py", line 395, in _loop_writing
self._write_fut = self._loop._proactor.send(self._sock, data)
AttributeError: 'NoneType' object has no attribute 'send'
Exception ignored in:
Traceback (most recent call last):
File "C:\Users\bujhm\AppData\Local\Programs\Python\Python39\lib\site-packages\aiomysql\connection.py", line 1120, in __del__
File "C:\Users\bujhm\AppData\Local\Programs\Python\Python39\lib\site-packages\aiomysql\connection.py", line 339, in close
File "C:\Users\bujhm\AppData\Local\Programs\Python\Python39\lib\asyncio\proactor_events.py", line 108, in close
File "C:\Users\bujhm\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 746, in call_soon
File "C:\Users\bujhm\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 510, in _check_closed
RuntimeError: Event loop is closed
  • Вопрос задан
  • 503 просмотра
Пригласить эксперта
Ответы на вопрос 1
@OldJaponec
Я не думаю, что законно дважды asyncio.run() вызывать
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Похожие вопросы