CommonService.py 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  1. # -*- coding: utf-8 -*-
  2. import datetime
  3. import time
  4. from pathlib import Path
  5. from random import Random
  6. import simplejson as json
  7. from django.core import serializers
  8. from django.utils import timezone
  9. from pyipip import IPIPDatabase
  10. from Ansjer.config import BASE_DIR
  11. # 复用性且公用较高封装代码在这
  12. class CommonService:
  13. # 添加模糊搜索
  14. @staticmethod
  15. def get_kwargs(data={}):
  16. kwargs = {}
  17. for (k, v) in data.items():
  18. if v is not None and v != u'':
  19. kwargs[k + '__icontains'] = v
  20. return kwargs
  21. # 定义静态方法
  22. # 格式化query_set转dict
  23. @staticmethod
  24. def qs_to_dict(query_set):
  25. sqlJSON = serializers.serialize('json', query_set)
  26. sqlList = json.loads(sqlJSON)
  27. sqlDict = dict(zip(["datas"], [sqlList]))
  28. return sqlDict
  29. # 获取文件大小
  30. @staticmethod
  31. def get_file_size(file_path='', suffix_type='', decimal_point=0):
  32. # for x in ['bytes', 'KB', 'MB', 'GB', 'TB']:
  33. # path = Path() / 'D:/TestServer/123444.mp4'
  34. path = Path() / file_path
  35. size = path.stat().st_size
  36. mb_size = 0.0
  37. if suffix_type == 'MB':
  38. mb_size = size / 1024.0 / 1024.0
  39. if decimal_point != 0:
  40. mb_size = round(mb_size, decimal_point)
  41. return mb_size
  42. @staticmethod
  43. def get_param_flag(data=[]):
  44. print(data)
  45. flag = True
  46. for v in data:
  47. if v is None:
  48. flag = False
  49. break
  50. return flag
  51. @staticmethod
  52. def get_ip_address(request):
  53. """
  54. 获取ip地址
  55. :param request:
  56. :return:
  57. """
  58. ip = request.META.get("HTTP_X_FORWARDED_FOR", "")
  59. if not ip:
  60. ip = request.META.get('REMOTE_ADDR', "")
  61. client_ip = ip.split(",")[-1].strip() if ip else ""
  62. return client_ip
  63. # @获取一天每个小时的datetime.datetime
  64. @staticmethod
  65. def getTimeDict(times):
  66. time_dict = {}
  67. t = 0
  68. for x in range(24):
  69. if x < 10:
  70. x = '0' + str(x)
  71. else:
  72. x = str(x)
  73. a = times.strftime("%Y-%m-%d") + " " + x + ":00:00"
  74. time_dict[t] = timezone.datetime.strptime(a, '%Y-%m-%d %H:%M:%S')
  75. t += 1
  76. return time_dict
  77. # 根据ip获取地址
  78. @staticmethod
  79. def getAddr(ip):
  80. base_dir = BASE_DIR
  81. # ip数据库
  82. db = IPIPDatabase(base_dir + '/DB/17monipdb.dat')
  83. addr = db.lookup(ip)
  84. ts = addr.split('\t')[0]
  85. return ts
  86. @staticmethod
  87. def getUserID(userPhone='13800138000', getUser=True, setOTAID=False, μs=True):
  88. if μs == True:
  89. if getUser == True:
  90. timeID = str(round(time.time() * 1000000))
  91. userID = timeID + userPhone
  92. return userID
  93. else:
  94. if setOTAID == False:
  95. timeID = str(round(time.time() * 1000000))
  96. ID = userPhone + timeID
  97. return ID
  98. else:
  99. timeID = str(round(time.time() * 1000000))
  100. eID = '13800' + timeID + '138000'
  101. return eID
  102. else:
  103. if getUser == True:
  104. timeID = str(round(time.time() * 1000))
  105. userID = timeID + userPhone
  106. return userID
  107. else:
  108. if setOTAID == False:
  109. timeID = str(round(time.time() * 1000))
  110. ID = userPhone + timeID
  111. return ID
  112. else:
  113. timeID = str(round(time.time() * 1000))
  114. eID = '13800' + timeID + '138000'
  115. return eID
  116. # 生成随机数
  117. @staticmethod
  118. def RandomStr(randomlength=8, number=True):
  119. str = ''
  120. if number == False:
  121. characterSet = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsT' \
  122. 'tUuVvWwXxYyZz0123456789'
  123. else:
  124. characterSet = '0123456789'
  125. length = len(characterSet) - 1
  126. random = Random()
  127. for index in range(randomlength):
  128. str += characterSet[random.randint(0, length)]
  129. return str
  130. # 生成订单好
  131. @staticmethod
  132. def createOrderID():
  133. random_id = CommonService.RandomStr(6, True)
  134. order_id = datetime.datetime.now().strftime('%Y%m%d%H%M%S') + str(random_id)
  135. print('orderID:')
  136. print(order_id)
  137. return order_id
  138. # qs转换list datetime处理
  139. @staticmethod
  140. def qs_to_list(qs):
  141. res = []
  142. # print(qs)
  143. for ps in qs:
  144. if 'add_time' in ps:
  145. ps['add_time'] = ps['add_time'].strftime("%Y-%m-%d %H:%M:%S")
  146. if 'update_time' in ps:
  147. ps['update_time'] = ps['update_time'].strftime("%Y-%m-%d %H:%M:%S")
  148. if 'end_time' in ps:
  149. ps['end_time'] = ps['end_time'].strftime("%Y-%m-%d %H:%M:%S")
  150. if 'data_joined' in ps:
  151. if ps['data_joined']:
  152. ps['data_joined'] = ps['data_joined'].strftime("%Y-%m-%d %H:%M:%S")
  153. else:
  154. ps['data_joined'] = ''
  155. res.append(ps)
  156. return res