Moved creating connection to MySQL DB to RawConnection class to get rid of global variables

This commit is contained in:
Forden 2020-04-13 21:41:29 +03:00
parent 2bbbee4651
commit 13ff8d0478

View File

@ -5,16 +5,10 @@ import aiomysql
from data import config from data import config
connection_pool = None
mainloop = asyncio.get_event_loop()
async def main(loop):
global connection_pool
connection_pool = await aiomysql.create_pool(**config.mysql_info, loop=loop)
class RawConnection: class RawConnection:
connection_pool = None
@staticmethod @staticmethod
async def _make_request( async def _make_request(
sql: str, sql: str,
@ -23,8 +17,9 @@ class RawConnection:
mult: bool = False, mult: bool = False,
retries_count: int = 5 retries_count: int = 5
) -> Optional[Union[List[Dict[str, Any]], Dict[str, Any]]]: ) -> Optional[Union[List[Dict[str, Any]], Dict[str, Any]]]:
global connection_pool if RawConnection.connection_pool is None:
async with connection_pool.acquire() as conn: RawConnection.connection_pool = await aiomysql.create_pool(**config.mysql_info)
async with RawConnection.connection_pool.acquire() as conn:
conn: aiomysql.Connection = conn conn: aiomysql.Connection = conn
async with conn.cursor(aiomysql.DictCursor) as cur: async with conn.cursor(aiomysql.DictCursor) as cur:
cur: aiomysql.DictCursor = cur cur: aiomysql.DictCursor = cur
@ -50,6 +45,3 @@ class RawConnection:
return r return r
else: else:
await conn.commit() await conn.commit()
mainloop.run_until_complete(main(mainloop))