Advertisement
ElRandir42

ElRandir's TGbot -- SQLiter

Nov 20th, 2019
235
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.69 KB | None | 0 0
  1. import asyncio
  2. import asyncpg
  3. from asyncpg.pool import Pool
  4. from asyncpg.connection import Connection
  5. from constants import PG_USER, PG_PASSWORD, PG_HOST, PG_PORT
  6.  
  7. loop = asyncio.get_event_loop()
  8.  
  9. _pool: Pool = loop.run_until_complete(
  10.     asyncpg.create_pool(
  11.         host=PG_HOST,
  12.         port=PG_PORT,
  13.         database="database",
  14.         user=PG_USER,
  15.         password=PG_PASSWORD
  16.     )
  17. )
  18.  
  19.  
  20. def connection(coro):
  21.     async def wrapper(*args, **kwargs):
  22.         async with _pool.acquire() as connect:  # берём соединение из пула соединений
  23.             async with connect.transaction():  # открываем для взятого соединения транзакцию
  24.                 return await coro(connect=connect, *args, **kwargs)  #
  25.     return wrapper
  26.  
  27.  
  28. @connection
  29. async def create_tables(connect: Connection):
  30.     await connect.execute("CREATE TABLE IF NOT EXISTS phones (id SERIAL PRIMARY KEY, phone TEXT UNIQUE)")
  31.     # ...
  32.  
  33.  
  34. @connection
  35. async def insert_phone(phone: str, connect: Connection):
  36.     await connect.execute("INSERT INTO phones (phone) VALUES ($1)", phone)
  37.  
  38. @connection
  39. async def check_connection(text_plz: str, connect: Connection):
  40.     await connect.execute("INSERT INTO dich_plz (text_plz) VALUES ($1)", text_plz)
  41.  
  42. @connection
  43. async def get_phone_record(phone: str, connect: Connection):
  44.     return await connect.fetchrow("SELECT * FROM phones WHERE phone=$1", phone)
  45.  
  46.  
  47. async def close():
  48.     await _pool.close()
  49.  
  50.  
  51. async def main():
  52.     try:
  53.         ...
  54.     finally:
  55.         await close()
  56.  
  57. if __name__ == '__main__':
  58.     try:
  59.         loop.run_until_complete(main())
  60.     finally:
  61.         loop.close()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement