views.py 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  1. from rest_framework.generics import GenericAPIView
  2. from rest_framework.response import Response
  3. import re
  4. import math
  5. from .serializers import ZhiBaoSelectViewSerializer
  6. from utils.JWTAuthentication_diy import MyJWTAuthentication
  7. from utils.permissions import ModulePermission
  8. from utils.db_utils import MongoDBTools
  9. from utils.all_dict import insect_dict
  10. from django.conf import settings
  11. class PestSelectView(GenericAPIView):
  12. authentication_classes = [MyJWTAuthentication]
  13. permission_classes = [ModulePermission]
  14. serializer_class = ZhiBaoSelectViewSerializer
  15. def get(self, request, *args, **kwargs):
  16. serializer = self.get_serializer(data=request.query_params)
  17. serializer.is_valid(raise_exception=True)
  18. data = serializer.validated_data
  19. identify_model = data["identify_model"]
  20. start_time = data["start_time"]
  21. end_time = data["end_time"]
  22. page = data["page"]
  23. page_size = data["page_size"]
  24. select_name = data.get("pest_name",'')
  25. if select_name:
  26. key_list=list(insect_dict.keys())
  27. val_list=list(insect_dict.values())
  28. ind = val_list.index(select_name)
  29. key = key_list[ind]+"," # 1665772530,1666125101
  30. wheres = {
  31. "photo_status": 1,
  32. "addtime": {
  33. "$gte": start_time,
  34. "$lt": end_time
  35. },
  36. "indentify_result": re.compile("#{}|^{}".format(key,key))
  37. }
  38. else:
  39. wheres = {
  40. "photo_status": 1,
  41. "addtime":{
  42. "$gte": start_time,
  43. "$lt": end_time
  44. },
  45. "indentify_result": {
  46. "$nin": ["", "0", None]
  47. }
  48. }
  49. project = {
  50. "device_id":"$device_id",
  51. "addr":"$addr",
  52. "indentify_photo":"$indentify_photo",
  53. "indentify_result": "$indentify_result",
  54. "addtime":"$addtime"
  55. }
  56. skip = (page-1)*page_size
  57. limit = page_size
  58. model = MongoDBTools(db_name='smartfarming', table_name='sa_device_cbdphoto') if identify_model == "A" else MongoDBTools(db_name='smartfarming', table_name='sa_device_cbdphoto_b')
  59. photo_data = model.find_many(wheres=wheres, options=project, skip=skip, limit=limit)
  60. if photo_data:
  61. total_counts = photo_data.count()
  62. else:
  63. total_counts = 0
  64. data = {"total_page":math.ceil(total_counts/page_size), "total_counts":total_counts, "page_size":page_size, "current_page":page, "current_counts":0, "items":[]}
  65. d_id_list = []
  66. items = []
  67. for i in photo_data:
  68. d_id_list.append(int(i["device_id"]))
  69. items.append(i)
  70. data["current_counts"] += 1
  71. wheres = {
  72. "device_type_id":3,
  73. "id": {
  74. "$in": d_id_list
  75. }
  76. }
  77. project = {
  78. 'id': "$id",
  79. 'device_id': '$device_id',
  80. 'device_name': '$device_name',
  81. 'device_code': '$device_code',
  82. 'province': '$province',
  83. 'city': '$city',
  84. 'district': '$district'
  85. }
  86. m = MongoDBTools(db_name='smartfarming', table_name='sa_device')
  87. device_data = m.find_many(wheres=wheres, options=project)
  88. d_id_dicts = {}
  89. for device_item in device_data:
  90. d_id_dicts[device_item["id"]] = {"location":device_item["province"]+device_item["city"]+device_item["district"],
  91. "device_id":device_item["device_id"],
  92. "device_code":device_item["device_code"],
  93. "device_name":device_item["device_name"] if device_item["device_name"] else "测报灯"
  94. }
  95. pest_image_data = []
  96. for photo_object in items:
  97. indentify_result = photo_object["indentify_result"]
  98. pest_string = ""
  99. pest_dict = {}
  100. for index,result in enumerate(indentify_result.split("#")) :
  101. if index != 0:
  102. pest_string += "、"
  103. tuple_result = result.split(",")
  104. pest_name = insect_dict.get(tuple_result[0],"未命名")
  105. pest_string+=pest_name
  106. pest_dict[pest_name] = int(tuple_result[1])
  107. addtime = photo_object["addtime"]
  108. d_id = int(photo_object["device_id"])
  109. device_code = d_id_dicts.get(d_id,{"device_code":0}).get("device_code",0)
  110. img_path = settings.CONFIG["image_url"]["image"]
  111. if identify_model == "A":
  112. indentify_path = settings.CONFIG["image_url"]["discern"]
  113. elif identify_model == "B" and device_code == 4: # 水稻
  114. indentify_path = settings.CONFIG["image_url"]["discern"]
  115. else:
  116. indentify_path = settings.CONFIG["image_url"]["discernB"]
  117. if photo_object["addr"].startswith("http"):
  118. img_url = photo_object["addr"]
  119. elif photo_object["addr"].startswith('/'):
  120. img_url = img_path + photo_object["addr"]
  121. else:
  122. img_url = img_path + "/" + photo_object["addr"]
  123. if photo_object["indentify_photo"]:
  124. if photo_object["indentify_photo"].startswith("http"):
  125. indentify_photo = photo_object["indentify_photo"]
  126. elif photo_object["indentify_photo"].startswith('/'):
  127. indentify_photo = indentify_path + photo_object["indentify_photo"]
  128. else:
  129. indentify_photo = indentify_path + "/" + photo_object["indentify_photo"]
  130. else:
  131. indentify_photo = ""
  132. pest_image_data.append({"deviceId":str(d_id_dicts.get(d_id,{"device_id":d_id})["device_id"]),
  133. "deviceName":d_id_dicts.get(d_id,{"device_name":"测报灯"})["device_name"],
  134. "pestName":pest_string,
  135. "addtime":addtime,
  136. "location":d_id_dicts.get(d_id,{"location":""})["location"],
  137. "img_url":img_url,
  138. "indentify_photo":indentify_photo,
  139. "pest_dict":pest_dict
  140. })
  141. data["items"] = pest_image_data
  142. return Response(data)
  143. class RecentMonthPestCount(GenericAPIView):
  144. authentication_classes = []
  145. permission_classes = []
  146. def get(self, request, *args, **kwargs):
  147. try:
  148. data=request.query_params
  149. start = data.get("start")
  150. end = data.get("end")
  151. device_id = data.get("device_id")
  152. m = MongoDBTools(db_name='smartfarming', table_name='sa_device')
  153. device = m.find_one(wheres={"device_id": device_id}, options={"id": 1})
  154. d_id = device.get("id")
  155. sa_device_cbdphoto_b = MongoDBTools(db_name='smartfarming', table_name='sa_device_cbdphoto_b')
  156. data = sa_device_cbdphoto_b.find_many(
  157. wheres={
  158. "device_id": str(d_id),
  159. "addtime": {
  160. "$gte": int(start),
  161. "$lte": int(end)
  162. }
  163. },
  164. options={
  165. "id": 1,
  166. "indentify_result": 1,
  167. "addr": 1
  168. }
  169. )
  170. # 17,1#158,5#365,5#260,7#20,1#46,2#160,6#3,1#21,1
  171. result = {}
  172. imgs = []
  173. for i in data:
  174. indentify_result = i.get("indentify_result")
  175. addr = i.get("addr")
  176. if indentify_result:
  177. iden = indentify_result.split("#")
  178. for p in iden:
  179. pest, num = p.split(",")
  180. if pest in result.keys():
  181. result[pest] += int(num)
  182. else:
  183. result[pest] = int(num)
  184. imgs.append(addr if addr.startswith("http") else "https://bigdata-image.oss-cn-hangzhou.aliyuncs.com/Basics/cbd/" + addr)
  185. data = {
  186. "pest": result,
  187. "imgs": imgs
  188. }
  189. return Response(data)
  190. except Exception as e:
  191. return Response({"data": [], "imgs": [], "msg": e.args})