Quellcode durchsuchen

批量绑定设备

linhaohong vor 1 Jahr
Ursprung
Commit
10e532b5f3
1 geänderte Dateien mit 80 neuen und 2 gelöschten Zeilen
  1. 80 2
      AdminController/CloudServiceManage/AgentDeviceController.py

+ 80 - 2
AdminController/CloudServiceManage/AgentDeviceController.py

@@ -6,12 +6,17 @@
 @Email   : zhangdongming@asj6.wecom.work
 @Software: PyCharm
 """
+import os
+import csv
+import time
 from datetime import datetime
 from dateutil.relativedelta import relativedelta
 from collections import defaultdict
 from decimal import Decimal
 import traceback
+import threading
 
+from django.db import transaction
 from django.http import QueryDict
 from django.views import View
 from django.core.paginator import Paginator
@@ -20,7 +25,7 @@ from AgentModel.models import AgentCustomerInfo, AgentDeviceOrder, AgentDevice,
 from Model.models import DeviceTypeModel
 
 from Object.ResponseObject import ResponseObject
-from Object.TokenObject import TokenObject
+from Ansjer.config import LOGGER
 
 
 class AgentDeviceView(View):
@@ -243,4 +248,77 @@ class AgentDeviceView(View):
 
         except Exception as e:
             error_msg = f"error_line:{traceback.format_exc()}, error_msg:{str(e)}"
-            return response.json(500, error_msg)
+            return response.json(500, error_msg)
+
+    def agent_devices_from_csv(self, ac_id, device_type, userID, file_path):
+        """
+        异步批量绑定设备
+        """
+        try:
+            with open(file_path, 'r') as file:
+                reader = csv.DictReader(file)
+                devices_to_create = []
+                existing_serial_numbers = set(AgentDevice.objects.values_list('serial_number', flat=True))
+
+                for row in reader:
+                    serial_number = row.get('serial_number')
+                    if serial_number not in existing_serial_numbers:
+                        device = AgentDevice(
+                            ac_id=ac_id,
+                            serial_number=serial_number,
+                            type=device_type,
+                            status=0,
+                            created_time=int(time.time()),
+                            created_by=userID,
+                            updated_time=int(time.time()),
+                            updated_by=userID
+                        )
+                        devices_to_create.append(device)
+                # 使用Django的bulk_create来批量创建对象
+                if devices_to_create:
+                    with transaction.atomic():
+                        AgentDevice.objects.bulk_create(devices_to_create, batch_size=200)
+
+            # 删除文件
+            os.remove(file_path)
+        except Exception as e:
+            LOGGER.info('errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
+
+    def batch_band_device(self, userID, request, request_dict, response):
+        """
+        批量绑定设备
+        @param ac_id: ac_id 代理商id
+        @param userID: userID
+        @param csv_file_path: 文件路径
+        @param response: 响应对象
+        @return:
+        """
+        ac_id = request_dict.get('ac_id', None)
+        device_name = request_dict.get('device_name', None)
+        csv_file = request.FILES['file']
+        upload_dir = os.path.join('static', 'uploaded_files')
+
+        if not all([ac_id, device_name]):
+            return response.json(444)
+
+        try:
+            device_type_dict = DeviceTypeModel.objects.filter(name=device_name).values('type').first()
+            device_type = device_type_dict['type']
+
+            if not os.path.exists(upload_dir):
+                os.makedirs(upload_dir)
+
+            file_path = os.path.join(upload_dir, csv_file.name)
+            with open(file_path, 'wb+') as destination:
+                for chunk in csv_file.chunks():
+                    destination.write(chunk)
+
+            # 创建并启动线程来异步执行任务
+            thread = threading.Thread(target=self.agent_devices_from_csv, args=(ac_id, device_type, userID, file_path))
+            thread.start()
+
+            return response.json(0)
+
+        except Exception as e:
+            print(e)
+            return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))