asyncDB.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. """
  2. @author: luojunhui
  3. """
  4. import aiomysql
  5. from aiomysql.cursors import Cursor
  6. from applications import log
  7. from config import env
  8. class AsyncMySQLClient(object):
  9. """
  10. Async MySQL
  11. """
  12. def __init__(self, app):
  13. self.app = app
  14. async def initPool(self):
  15. """
  16. 初始化连接
  17. :return:
  18. """
  19. if env == "prod":
  20. self.app.mysql_pool = await aiomysql.create_pool(
  21. host='rm-bp1159bu17li9hi94.mysql.rds.aliyuncs.com',
  22. port=3306,
  23. user='crawler',
  24. password='crawler123456@',
  25. db='piaoquan-crawler',
  26. charset='utf8mb4',
  27. maxsize=100,
  28. connect_timeout=120,
  29. )
  30. log(
  31. code="1001",
  32. env=env,
  33. message="数据库初始化成功"
  34. )
  35. elif env == "dev":
  36. self.app.mysql_pool = await aiomysql.create_pool(
  37. host='rm-bp1k5853td1r25g3n690.mysql.rds.aliyuncs.com',
  38. port=3306,
  39. user='crawler',
  40. password='crawler123456@',
  41. db='piaoquan-crawler',
  42. charset='utf8mb4',
  43. maxsize=100,
  44. connect_timeout=120,
  45. )
  46. log(
  47. code="1001",
  48. env=env,
  49. message="数据库初始化成功"
  50. )
  51. else:
  52. log(
  53. code="1001",
  54. env=env,
  55. message="数据库初始化失败,环境校验失败"
  56. )
  57. return None
  58. async def closePool(self):
  59. """
  60. 关闭 mysql 连接
  61. :return:
  62. """
  63. self.app.mysql_pool.close()
  64. await self.app.mysql_pool.wait_closed()
  65. async def asyncSelect(self, sql, cursor_type=Cursor):
  66. """
  67. select method
  68. :param sql:
  69. :param cursor_type:
  70. :return:
  71. """
  72. async with self.app.mysql_pool.acquire() as conn:
  73. async with conn.cursor(cursor_type) as cursor:
  74. await cursor.execute(sql)
  75. result = await cursor.fetchall()
  76. return result
  77. async def asyncInsert(self, sql, params):
  78. """
  79. insert and update method
  80. :param params:
  81. :param sql:
  82. :return:
  83. """
  84. async with self.app.mysql_pool.acquire() as coon:
  85. async with coon.cursor() as cursor:
  86. await cursor.execute(sql, params)
  87. await coon.commit()