Browse Source

最新代码

tanghongbin 5 years ago
parent
commit
e6e1999b6e
5 changed files with 150 additions and 15 deletions
  1. 17 0
      .gitignore
  2. 77 13
      Controller/FileController.py
  3. 15 1
      Model/models.py
  4. 2 0
      Object/ResponseObject.py
  5. 39 1
      Service/CommonService.py

+ 17 - 0
.gitignore

@@ -0,0 +1,17 @@
+/.idea
+/static
+/Model/migrations
+/AnsjerUIDManage/__pycache__
+/Controller/__pycache__
+/Model/__pycache__
+/Object/__pycache__
+/Service/__pycache__
+*.log
+*/__pycache__
+/AnsjerUIDManage/test/__pycache__
+/AnsjerUIDManage/test/__init__.py
+/sdk_install
+/DB/mydata4vipday2.ipdb
+/__pycache__/*.pyc
+/venv
+db.sqlite3

+ 77 - 13
Controller/FileController.py

@@ -9,8 +9,9 @@ from django.http import StreamingHttpResponse, HttpResponse, QueryDict
 from django.utils.decorators import method_decorator
 from django.views import View
 from django.views.decorators.csrf import csrf_exempt
+from django.db import transaction
 
-from Model.models import UIDModel, UserUIDModel, UserModel, LogModel
+from Model.models import UIDModel, UserUIDModel, UserModel, LogModel, MacModel
 from Object.RedisObject import RedisObject
 from Object.TokenObject import TokenObject
 from Object.ResponseObject import ResponseObject
@@ -47,6 +48,7 @@ class UploadUIDFileView(View):
         content = content[3:(len(content) - 3)]
         uids = content.split('\n')
         print(uids)
+        print(len(uids))
 
         response = ResponseObject()
 
@@ -71,13 +73,22 @@ class UploadUIDFileView(View):
         else:
             return self.do_reset(data, response, area, request, tko)
 
+    @transaction.atomic
     def do_insert(self, data, duplicate, area, response, request, token):
         bulk = []
         count = 0
         add_time = int(time.time())
         update_time = int(time.time())
         keys = data.keys()
+
+        # 获取最新的mac
+        mac = MacModel.objects.filter().values('id', 'value', 'is_active')[0]
+        if not mac['is_active']:
+            return response.json(175)
         # redisObject = RedisObject(db=3)
+        key = ''
+        tmpMac = mac['value']
+        savePoint = None
         for item in keys:
             key = item.strip()
             # value = redisObject.get_data(key)
@@ -92,28 +103,74 @@ class UploadUIDFileView(View):
                 status=0,
                 add_time=add_time,
                 update_time=update_time,
-                area=area
+                area=area,
+                mac=mac['value']
             ))
             try:
-                if (count % 5000) == 0:
-                    UIDModel.objects.bulk_create(bulk)
-                    bulk.clear()
+                try:
+                    if (count % 5000) == 0:
+                        savePoint = transaction.savepoint()
+                        UIDModel.objects.bulk_create(bulk)
+                        bulk.clear()
+                        data = {
+                            'value': mac['value'],
+                            'is_active': tmpMac is not None
+                        }
+                        MacModel.objects.filter().update(**data)
+                except Exception as e:
+                    # print('--------------------------error 5000')
+                    # print(repr(e))
+                    if savePoint:
+                        transaction.rollback(savePoint)
+                    return response.json(174, str(e))
+                else:
+                    savePoint = None
             except Exception as e:
-                print(repr(e))
+                # print('--------------------------error 5001')
+                # print(repr(e))
                 return response.json(174, str(e))
             count += 1
+            tmpMac = CommonService.updateMac(mac['value'])
+            if tmpMac is None:
+                # 能分配的mac已用完
+                break
+            else:
+                mac['value'] = tmpMac
 
-        if len(bulk) > 0:
-            UIDModel.objects.bulk_create(bulk)
-            bulk.clear()
-        del data
-        del bulk
+        # 当bulk不足5000时,还有数据要插入
+        try:
+            try:
+                savePoint = transaction.savepoint()  # 事务保存点
+                if len(bulk) > 0:
+                    UIDModel.objects.bulk_create(bulk)
+                    bulk.clear()
+            except Exception as e:
+                # print('--------------------------error')
+                # print(repr(e))
+                if savePoint:
+                    transaction.rollback(savePoint)
+                return response.json(174)
+            else:
+                del data
+                del bulk
+                data = {
+                    'value': mac['value'],
+                    'is_active': tmpMac is not None
+                }
+                MacModel.objects.filter().update(**data)
+        except Exception as e:
+            # print('--------------------------error 1111')
+            # print(repr(e))
+            return response.json(174)
 
         # print('重复:')
         # print(duplicate)
 
         operation = self.formatOperation(operation='上传', quantity=int(count), area=int(area))
         self.add_log(request, operation, token)
+
+        if tmpMac is None:
+            return response.json(175, {'last_uid': key})
         return response.json(0, {'count': count, 'duplicate_count': len(duplicate), 'data': duplicate})
 
     def do_reset(self, data, response, area, request, token):
@@ -172,6 +229,7 @@ class UploadUIDFileView(View):
         else:
             return str.format(operation=operation, quantity=quantity, area='国外')
 
+
 class DownloadUIDFileView(View):
 
     @method_decorator(csrf_exempt)
@@ -209,7 +267,7 @@ class DownloadUIDFileView(View):
         if area >= 0 and quantity > 0:
 
             uid_qs = UserUIDModel.objects.filter(user__id=token.userID, uid__status=1, uid__area=area). \
-                values('uid__id', 'uid__uid', 'uid__uid_extra', 'uid__add_time', 'uid__update_time', 'uid__area')
+                values('uid__id', 'uid__uid', 'uid__mac', 'uid__uid_extra', 'uid__add_time', 'uid__update_time', 'uid__area')
             count = uid_qs.count()
             if count < quantity:
                 return response.json(444, '设备UID不足')
@@ -231,11 +289,17 @@ class DownloadUIDFileView(View):
         updates = []
         content = ''
         for item in uid_qs:
+            # print(item)
+            mac: str = item['uid__mac']
+            index = mac.rfind(':')
+            tmp = mac[0:index] + '\t' + mac[index:]
+            content += tmp + '\t'
             content += item['uid__uid']
-            content += '\n'
+            content += '\r\n'
             updates.append(UIDModel(
                 id=item['uid__id'],
                 uid=item['uid__uid'],
+                mac=item['uid__mac'],
                 uid_extra=item['uid__uid_extra'],
                 status=2,
                 add_time=item['uid__add_time'],

+ 15 - 1
Model/models.py

@@ -20,6 +20,7 @@ class UserModel(models.Model):
 class UIDModel(models.Model):
     id = models.AutoField(primary_key=True)
     uid = models.CharField(max_length=20, null=False, db_index=True, unique=True, verbose_name='设备id')
+    mac = models.CharField(max_length=17, null=False, default='', verbose_name='设备id对应的mac地址')
     uid_extra = models.TextField(default='', verbose_name='uid的额外描述')
     status = models.SmallIntegerField(default=0, verbose_name='使用状态')
     add_time = models.IntegerField(default=0, verbose_name='添加时间')
@@ -73,7 +74,7 @@ class LogModel(models.Model):
 
 class HistoryUIDModel(models.Model):
     id = models.AutoField(primary_key=True)
-    uid = models.CharField(max_length=20, null=False, db_index=True, unique=True, verbose_name='设备id')
+    uid = models.CharField(max_length=20, null=False, db_index=True, verbose_name='设备id')
     uid_extra = models.TextField(default='', verbose_name='uid的额外描述')
     status = models.SmallIntegerField(default=0, verbose_name='使用状态')
     add_time = models.IntegerField(default=0, verbose_name='添加时间')
@@ -86,3 +87,16 @@ class HistoryUIDModel(models.Model):
         db_table = 'history_uid'
 
 
+class MacModel(models.Model):
+    id = models.AutoField(primary_key=True)
+    value = models.CharField(max_length=17, null=False, verbose_name='最新的mac地址')
+    is_active = models.BooleanField(default=True, verbose_name='当前mac地址是否可用')
+    add_time = models.IntegerField(default=0, verbose_name='添加时间')
+    update_time = models.IntegerField(default=0, verbose_name='更新时间')
+
+    class Meta:
+        verbose_name = '最新的mac地址表'
+        verbose_name_plural = verbose_name
+        db_table = 'tb_mac'
+
+

+ 2 - 0
Object/ResponseObject.py

@@ -37,6 +37,7 @@ class ResponseObject(object):
             138: '手机格式不符合规则!',
             173: '数据不存在!',
             174: '数据已存在',
+            175: 'mac地址已用完',
             305: '令牌格式是错误的,相关参数是不存在的!',
             307: '令牌已过期!',
             309: '你没有权限访问',
@@ -74,6 +75,7 @@ class ResponseObject(object):
             138: 'The phone format does not conform to the rules! ',
             173: 'Data does not exists!',
             174: 'Data already exists',
+            175: 'MAC address has been used up',
             305: 'The Token format is wrong and the related parameter is None!',
             307: 'The Token has expired!',
             309: 'You have no access',

+ 39 - 1
Service/CommonService.py

@@ -221,4 +221,42 @@ class CommonService:
         random = Random()
         for index in range(randomlength):
             str += characterSet[random.randint(0, length)]
-        return str
+        return str
+
+    @staticmethod
+    def updateMac(mac: str):
+        macArray = mac.split(':')
+
+        macArray[0] = int(macArray[0], 16)
+        macArray[1] = int(macArray[1], 16)
+        macArray[2] = int(macArray[2], 16)
+        first = int(macArray[5], 16)
+        second = int(macArray[4], 16)
+        three = int(macArray[3], 16)
+
+        # print(macArray)
+        # print(first)
+        # print(second)
+        # print(three)
+
+        if first == 255 and second == 255 and three == 255:
+            return None
+
+        first += 1
+
+        if first / 256 == 1:
+            second += 1
+            first = first % 256
+
+        if second / 256 == 1:
+            three += 1
+            second = second % 256
+
+        macArray[3] = three
+        macArray[4] = second
+        macArray[5] = first
+        # print(macArray)
+
+        tmp = ':'.join(map(lambda x: "%02x" % x, macArray))
+        # print(tmp)
+        return tmp.upper()