Advertisement
Guest User

Untitled

a guest
Sep 13th, 2017
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.58 KB | None | 0 0
  1. import asyncio
  2. import aiomysql
  3.  
  4.  
  5. loop = asyncio.get_event_loop()
  6.  
  7.  
  8. # async def main(all_done):
  9. # """Get all messages."""
  10. # conn = await aiomysql.connect(host='127.0.0.1', port=3306, user='test',
  11. # password='test123', db='test', loop=loop)
  12. #
  13. # cur = await conn.cursor(aiomysql.DictCursor)
  14. # await cur.execute("SELECT receiver, message FROM messages")
  15. # r = await cur.fetchall()
  16. #
  17. # await cur.close()
  18. # conn.close()
  19. # all_done.set_result(r)
  20.  
  21.  
  22. class DBConnection(object):
  23. """Async context manager that makes a connection to db."""
  24.  
  25. def __init__(self, host, port, user, password, db):
  26. self.conn = None
  27. self.cur = None
  28. self.host = host
  29. self.port = port
  30. self.user = user
  31. self.password = password
  32. self.db = db
  33.  
  34. async def __aenter__(self):
  35. """Enter async context manager."""
  36. self.conn = await aiomysql.connect(host=self.host, port=self.port,
  37. user=self.user, password=self.password, db=self.db, loop=loop)
  38.  
  39. self.cur = await self.conn.cursor(aiomysql.DictCursor)
  40. return self.cur
  41.  
  42. async def __aexit__(self, *args):
  43. """Exit async context manager."""
  44. await self.cur.close()
  45. self.conn.close()
  46.  
  47.  
  48. async def alternative(all_done):
  49. """Get all messages."""
  50.  
  51. async with DBConnection(host='127.0.0.1', port=3306, user='test',
  52. password='test123', db='test') as cur:
  53. await cur.execute("SELECT receiver, message FROM messages")
  54. r = await cur.fetchall()
  55. all_done.set_result(r)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement