TC-b64

asyncpg

Nov 5th, 2019
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.47 KB | None | 0 0
  1. import asyncpg
  2. from asyncpg.pool import Pool
  3. from asyncpg.connection import Connection
  4. import asyncio
  5.  
  6.  
  7. loop = asyncio.get_event_loop()
  8.  
  9. _pool: Pool = loop.run_until_complete(
  10.     asyncpg.create_pool(
  11.         host="localhost",
  12.         port=5432,
  13.         database="bot_db",
  14.         user="postgres",
  15.         password="postgrespswd"
  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.  
  39. @connection
  40. async def get_phone_record(phone: str, connect: Connection):
  41.     return await connect.fetchrow("SELECT * FROM phones WHERE phone=$1", phone)
  42.  
  43.  
  44. async def close():
  45.     await _pool.close()
  46.  
  47.  
  48. async def main():
  49.     try:
  50.         ...
  51.     finally:
  52.         await close()
  53.  
  54.  
  55. if __name__ == '__main__':
  56.     try:
  57.         loop.run_until_complete(main())
  58.     finally:
  59.         loop.close()
Add Comment
Please, Sign In to add comment