CronDelDataController.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. #!/usr/bin/python3.6
  2. # -*- coding: utf-8 -*-
  3. #
  4. # Copyright (C) 2022 #
  5. # @Time : 2022/4/1 11:27
  6. # @Author : ming
  7. # @Email : zhangdongming@asj6.wecom.work
  8. # @File : CronDelDataController.py
  9. # @Software: PyCharm
  10. import time
  11. from django.db import connection, connections
  12. from django.views import View
  13. from Object.ResponseObject import ResponseObject
  14. from Object.utils import LocalDateTimeUtil
  15. class CronDelDataView(View):
  16. def get(self, request, *args, **kwargs):
  17. request.encoding = 'utf-8'
  18. operation = kwargs.get('operation')
  19. return self.validation(request.GET, request, operation)
  20. def post(self, request, *args, **kwargs):
  21. request.encoding = 'utf-8'
  22. operation = kwargs.get('operation')
  23. return self.validation(request.POST, request, operation)
  24. def validation(self, request_dict, request, operation):
  25. response = ResponseObject()
  26. if operation == 'access-log/del': # 定时删除访问接口数据
  27. return self.del_access_log(response)
  28. elif operation == 'push-info/del': # 定时删除推送数据
  29. return self.del_push_info(response)
  30. else:
  31. return response.json(404)
  32. @staticmethod
  33. def del_access_log(response):
  34. try:
  35. cursor = connection.cursor()
  36. # 删除一个月前的数据
  37. last_month = LocalDateTimeUtil.get_last_month()
  38. sql = 'DELETE FROM access_log WHERE time < %s limit %s'
  39. cursor.execute(sql, [last_month, 10000])
  40. # 关闭游标
  41. cursor.close()
  42. connection.close()
  43. return response.json(0)
  44. except Exception as e:
  45. return response.json(500, repr(e))
  46. @staticmethod
  47. def del_push_info(response):
  48. nowTime = int(time.time())
  49. cursor = connections['mysql02'].cursor()
  50. try:
  51. for i in range(5):
  52. # 删除7天前的数据
  53. sql = "DELETE FROM `equipment_info` WHERE addTime<={} LIMIT 10000".format(nowTime - 3600 * 24 * 7)
  54. cursor.execute(sql)
  55. # 关闭游标
  56. cursor.close()
  57. return response.json(0)
  58. except Exception as e:
  59. return response.json(500, repr(e))