CloudPhotoController.py 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122
  1. # -*- encoding: utf-8 -*-
  2. """
  3. @File : CloudPhotoController.py
  4. @Time : 2022/10/24 15:48
  5. @Author : stephen
  6. @Email : zhangdongming@asj6.wecom.work
  7. @Software: PyCharm
  8. """
  9. import datetime
  10. import logging
  11. import time
  12. import traceback
  13. from django.views import View
  14. from Ansjer.cn_config.config_formal import PUSH_CLOUD_PHOTO
  15. from Ansjer.config import ACCESS_KEY_ID, SECRET_ACCESS_KEY, REGION_NAME, PUSH_BUCKET
  16. from Model.models import UidSetModel, DeviceCloudPhotoInfo, DevicePicturePushInfo
  17. from Object.AWS.AmazonS3Util import AmazonS3Util
  18. from Object.RedisObject import RedisObject
  19. from Object.ResponseObject import ResponseObject
  20. from Service.EquipmentInfoService import EquipmentInfoService
  21. LOGGER = logging.getLogger('info')
  22. UID_KEY = 'ANSJER:UID:SET:INFO'
  23. class CloudPhotoView(View):
  24. def get(self, request, *args, **kwargs):
  25. request.encoding = 'utf-8'
  26. operation = kwargs.get('operation')
  27. return self.validation(request.GET, request, operation)
  28. def post(self, request, *args, **kwargs):
  29. request.encoding = 'utf-8'
  30. operation = kwargs.get('operation')
  31. return self.validation(request.POST, request, operation)
  32. def validation(self, request_dict, request, operation):
  33. response = ResponseObject()
  34. if operation == 'get-photo':
  35. return self.get_photo(response)
  36. elif operation == 'cache-uid-set':
  37. return self.cache_photo_uid_set(response)
  38. else:
  39. return response.json(404)
  40. @classmethod
  41. def get_photo(cls, response):
  42. """
  43. 定时获取云存消息推送图
  44. """
  45. try:
  46. redis = RedisObject().CONN
  47. uid_set_cache = redis.lrange(UID_KEY, 0, -1)
  48. if not uid_set_cache:
  49. return response.json(0)
  50. uid_set_cache = list(uid_set_cache)
  51. today = datetime.date.today()
  52. start_time = "{} 00:00:00".format(str(today))
  53. # 先转换为时间数组
  54. timeArray = time.strptime(start_time, "%Y-%m-%d %H:%M:%S")
  55. # 转换为时间戳
  56. timeStamp = int(time.mktime(timeArray))
  57. now_time = int(time.time())
  58. for item in uid_set_cache:
  59. try:
  60. eq_qs = EquipmentInfoService.get_equipment_info_model(str(today))
  61. item = str(item, encoding="utf-8")
  62. eq_qs = eq_qs.filter(event_time__gt=timeStamp, is_st=1, device_uid=item) \
  63. .values('device_uid', 'channel', 'event_time')
  64. count = eq_qs.count()
  65. page = int(count / 2) if count > 1 else count
  66. redis.lrem(UID_KEY, 0, item)
  67. if page == 0:
  68. continue
  69. eq_qs = eq_qs[(page - 1) * 1:page * 1]
  70. eq_vo = eq_qs[0]
  71. s3 = AmazonS3Util(
  72. aws_access_key_id=ACCESS_KEY_ID,
  73. secret_access_key=SECRET_ACCESS_KEY,
  74. region_name=REGION_NAME
  75. )
  76. file_path = '{uid}/{channel}/{event_time}.jpeg'.format(uid=eq_vo['device_uid'],
  77. channel=eq_vo['channel'],
  78. event_time=eq_vo['event_time'])
  79. s3.copy_obj(PUSH_BUCKET, PUSH_CLOUD_PHOTO, file_path)
  80. push_data = {'type': 1, 'uid': eq_vo['device_uid'], 'channel': eq_vo['channel'],
  81. 'event_time': eq_vo['event_time'], 'updated_time': now_time, 'created_time': now_time}
  82. DevicePicturePushInfo.objects.create(**push_data)
  83. except Exception as e:
  84. LOGGER.info('异常详情,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  85. continue
  86. return response.json(0)
  87. except Exception as e:
  88. print(e)
  89. LOGGER.info('--->抽取推送图片异常:{}'.format(traceback.format_exc()))
  90. return response.json(177, repr(e))
  91. @classmethod
  92. def cache_photo_uid_set(cls, response):
  93. """
  94. 缓存uid_set
  95. @return:
  96. """
  97. try:
  98. photo_qs = DeviceCloudPhotoInfo.objects.filter(status=1).values('uid')
  99. if not photo_qs.exists():
  100. return response.json(0)
  101. redis = RedisObject()
  102. for item in photo_qs:
  103. uid_set_qs = UidSetModel.objects.filter(uid=item['uid'], detect_status=1)
  104. if not uid_set_qs:
  105. continue
  106. redis.CONN.rpush(UID_KEY, item['uid'])
  107. return response.json(0)
  108. except Exception as e:
  109. print(e)
  110. LOGGER.info('--->获取uid_set信息异常:{}'.format(traceback.format_exc()))
  111. return response.json(177, repr(e))