task2.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. """
  2. @author: luojunhui
  3. """
  4. import time
  5. import datetime
  6. import asyncio
  7. import aiomysql
  8. from applications.deal.process_deal_2 import ProcessDeal2
  9. class TaskMySQLClient(object):
  10. """
  11. Async MySQL
  12. """
  13. def __init__(self):
  14. self.mysql_pool = None
  15. async def init_pool(self):
  16. """
  17. 初始化连接
  18. :return:
  19. """
  20. self.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. connect_timeout=120,
  28. )
  29. print("mysql init successfully")
  30. async def close_pool(self):
  31. """
  32. 关闭 mysql 连接
  33. :return:
  34. """
  35. self.mysql_pool.close()
  36. await self.mysql_pool.wait_closed()
  37. async def async_select(self, sql):
  38. """
  39. select method
  40. :param sql:
  41. :return:
  42. """
  43. async with self.mysql_pool.acquire() as conn:
  44. async with conn.cursor() as cursor:
  45. await cursor.execute(sql)
  46. result = await cursor.fetchall()
  47. return result
  48. async def async_insert(self, sql):
  49. """
  50. insert and update method
  51. :param sql:
  52. :return:
  53. """
  54. async with self.mysql_pool.acquire() as coon:
  55. async with coon.cursor() as cursor:
  56. await cursor.execute(sql)
  57. await coon.commit()
  58. async def main():
  59. """
  60. main job
  61. :return:
  62. """
  63. TMC = TaskMySQLClient()
  64. await TMC.init_pool()
  65. PD = ProcessDeal2(TMC)
  66. await PD.deal()
  67. if __name__ == '__main__':
  68. while True:
  69. asyncio.run(main())
  70. now_str = datetime.datetime.now().__str__()
  71. print("{} 请求执行完成, 等待120s".format(now_str))
  72. time.sleep(120)