Ver código fonte

设备导入接口

zhangnaiwen 2 anos atrás
pai
commit
552d5808e4

+ 3 - 0
config/config.yml

@@ -3,6 +3,9 @@ common:
   JWT_EXPIRY: 86400
   MESSAGR_TYPE: ["普通消息","提醒消息"]
   INFORMATION_TYPE: ["楼层地图信息配置", "安保人员信息配置"]
+
+  # 设备Excel存醋位置
+  DEVICE_EXCEL_SAVE_PATH: /data/device
   # 公司商标存储地址
   COMPANY_LOGO_PATH: /data/company_logo
   COMPANY_LOGO_URL: http://127.0.0.1/company_logo/

BIN
config/device.xlsx


+ 82 - 1
src/app/api/device.py

@@ -1,9 +1,13 @@
 import json
+import os
 
-from flask import request, jsonify, g, current_app
+import xlrd
+from flask import request, jsonify, g, current_app, Response
 from flask_restx import Resource, Namespace, reqparse
 from sqlalchemy import select, insert, update, delete, func
+from sqlalchemy.exc import IntegrityError
 from sqlalchemy.orm import Session
+from werkzeug.datastructures import FileStorage
 
 from app.defines import StatesCode, Module, OperationType
 from app.modle.device import DeviceType, SecurityDevice
@@ -330,3 +334,80 @@ class BatchDeleteDeviceApi(Resource):
             save_log(request, Module.DEVICE, OperationType.DELETE, StatesCode.UNKNOWN_ERROR)
 
             return jsonify(code=StatesCode.UNKNOWN_ERROR, message=str(e))
+
+
+import_device = reqparse.RequestParser(bundle_errors=True)
+import_device.add_argument(name='files', type=FileStorage, required=True, location='files', help='导入设备Excel')
+
+
+@ns.route('/import_device')
+class ImportDeviceApi(Resource):
+    @ns.doc(id='import_device', description='导入模版下载')
+    def get(self):
+        """导入模版下载"""
+
+        manage_path = os.path.dirname(os.path.abspath(__file__))
+        config_yml_path = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(manage_path))), 'config',
+                                       'device.xlsx')
+
+        file_data = open(config_yml_path, 'rb')
+        buf = file_data.read()
+        file_data.close()
+
+        response = Response(buf)
+        response.headers['Content-Type'] = 'application/octet-stream'
+        response.headers['Content-Disposition'] = 'attachment; filename=%s' % 'device.xlsx'
+        return response
+
+    @ns.doc(id='import_device', description='设备导入')
+    @ns.expect(import_device)
+    def post(self):
+        """设备导入"""
+        device_file = request.files.get('files')
+
+        device_file_path = os.path.join(config.common.DEVICE_EXCEL_SAVE_PATH, device_file.name)
+        device_file.save(device_file_path)
+
+        xlsx = xlrd.open_workbook(device_file_path)
+
+        with Session(current_app.engine) as session:
+
+            for sheet in xlsx.sheets():
+                device_group = sheet.name
+
+                try:
+                    # 添加类别
+                    add_device_group = insert(DeviceType).values(
+                        type_name=device_group
+                    )
+                    session.execute(add_device_group)
+                    session.commit()
+                except IntegrityError:
+                    session.rollback()
+
+                # 获取类别id
+                get_device_group_id = select(DeviceType.id).where(DeviceType.type_name == device_group)
+                device_group_id = session.execute(get_device_group_id).scalars().first()
+
+                # 添加设备数据
+                for i in range(1, sheet.nrows):  # 逐行打印sheet数据
+                    value = sheet.row_values(i)
+                    add_device = insert(SecurityDevice).values(
+                        device_name=value[0],
+                        device_id=value[1],
+                        device_type=int(value[2]) if value[2] != '' else None,
+                        device_location=value[3],
+                        device_age=int(value[4]) if value[4] != '' else None,
+                        company_id=value[5],
+                        user_id=value[6],
+                        device_group=device_group_id,
+                        status=int(value[7]) if value[7] != '' else None,
+                        floor_id=int(value[8]) if value[8] != '' else None,
+                        third_id=value[9]
+                    )
+                    session.execute(add_device)
+                    session.commit()
+
+        save_log(request, Module.DEVICE, OperationType.IMPORT, StatesCode.SUCCESS)
+
+        return jsonify(code=StatesCode.SUCCESS, message='成功')

+ 1 - 0
src/app/defines/__init__.py

@@ -28,3 +28,4 @@ class OperationType:
     BATCH_UPDATE = '批量修改'
     BATCH_DELETE = '批量删除'
     EXPORT = '导出'
+    IMPORT = '导入'

+ 2 - 2
src/app/modle/device.py

@@ -1,4 +1,4 @@
-from sqlalchemy import String, Column, Integer, Float
+from sqlalchemy import String, Column, Integer
 
 from app.modle import Base
 
@@ -9,7 +9,7 @@ class DeviceType(Base):
     __tablename__ = 'security_device_type'
 
     id = Column(Integer, primary_key=True, autoincrement=True, nullable=False, unique=True, doc='id')
-    type_name = Column(String, nullable=False, unique=False, index=False, doc='类别名称', comment='类别名称')
+    type_name = Column(String, nullable=False, unique=True, index=False, doc='类别名称', comment='类别名称')
 
 
 class SecurityDevice(Base):