task.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. """
  2. @author: luojunhui
  3. """
  4. import time
  5. import asyncio
  6. import aiomysql
  7. from applications.deal import ProcessDeal
  8. class TaskMySQLClient(object):
  9. """
  10. Async MySQL
  11. """
  12. def __init__(self):
  13. self.mysql_pool = None
  14. async def init_pool(self):
  15. """
  16. 初始化连接
  17. :return:
  18. """
  19. self.mysql_pool = await aiomysql.create_pool(
  20. host='rm-bp1159bu17li9hi94.mysql.rds.aliyuncs.com',
  21. port=3306,
  22. user='crawler',
  23. password='crawler123456@',
  24. db='piaoquan-crawler',
  25. charset='utf8mb4',
  26. connect_timeout=120,
  27. )
  28. print("mysql init successfully")
  29. async def close_pool(self):
  30. """
  31. 关闭 mysql 连接
  32. :return:
  33. """
  34. self.mysql_pool.close()
  35. await self.mysql_pool.wait_closed()
  36. async def async_select(self, sql):
  37. """
  38. select method
  39. :param sql:
  40. :return:
  41. """
  42. async with self.mysql_pool.acquire() as conn:
  43. async with conn.cursor() as cursor:
  44. await cursor.execute(sql)
  45. result = await cursor.fetchall()
  46. return result
  47. async def async_insert(self, sql):
  48. """
  49. insert and update method
  50. :param sql:
  51. :return:
  52. """
  53. async with self.mysql_pool.acquire() as coon:
  54. async with coon.cursor() as cursor:
  55. await cursor.execute(sql)
  56. await coon.commit()
  57. async def main():
  58. """
  59. main job
  60. :return:
  61. """
  62. TMC = TaskMySQLClient()
  63. await TMC.init_pool()
  64. PD = ProcessDeal(TMC)
  65. await PD.deal()
  66. if __name__ == '__main__':
  67. while True:
  68. asyncio.run(main())
  69. print("请求执行完成, 等待120s")
  70. time.sleep(120)