CommonService.py 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  1. # -*- coding: utf-8 -*-
  2. import datetime
  3. import time
  4. from pathlib import Path
  5. from random import Random
  6. import ipdb
  7. import simplejson as json
  8. from django.core import serializers
  9. from django.utils import timezone
  10. from pyipip import IPIPDatabase
  11. from AnsjerUIDManage.config import BASE_DIR, UNICODE_ASCII_CHARACTER_SET
  12. # 复用性且公用较高封装代码在这
  13. class CommonService:
  14. # 添加模糊搜索
  15. @staticmethod
  16. def get_kwargs(data={}):
  17. kwargs = {}
  18. for (k, v) in data.items():
  19. if v is not None and v != u'':
  20. kwargs[k + '__icontains'] = v
  21. return kwargs
  22. # 定义静态方法
  23. # 格式化query_set转dict
  24. @staticmethod
  25. def qs_to_dict(query_set):
  26. sqlJSON = serializers.serialize('json', query_set)
  27. sqlList = json.loads(sqlJSON)
  28. sqlDict = dict(zip(["datas"], [sqlList]))
  29. return sqlDict
  30. # 获取文件大小
  31. @staticmethod
  32. def get_file_size(file_path='', suffix_type='', decimal_point=0):
  33. # for x in ['bytes', 'KB', 'MB', 'GB', 'TB']:
  34. # path = Path() / 'D:/TestServer/123444.mp4'
  35. path = Path() / file_path
  36. size = path.stat().st_size
  37. mb_size = 0.0
  38. if suffix_type == 'MB':
  39. mb_size = size / 1024.0 / 1024.0
  40. if decimal_point != 0:
  41. mb_size = round(mb_size, decimal_point)
  42. return mb_size
  43. @staticmethod
  44. def get_param_flag(data=[]):
  45. # print(data)
  46. flag = True
  47. for v in data:
  48. if v is None:
  49. flag = False
  50. break
  51. return flag
  52. @staticmethod
  53. def get_ip_address(request):
  54. """
  55. 获取ip地址
  56. :param request:
  57. :return:
  58. """
  59. try:
  60. real_ip = request.META['HTTP_X_FORWARDED_FOR']
  61. clientIP = real_ip.split(",")[0]
  62. except:
  63. try:
  64. clientIP = request.META['REMOTE_ADDR']
  65. except Exception as e:
  66. clientIP = ''
  67. return clientIP
  68. # @获取一天每个小时的datetime.datetime
  69. @staticmethod
  70. def getTimeDict(times):
  71. time_dict = {}
  72. t = 0
  73. for x in range(24):
  74. if x < 10:
  75. x = '0' + str(x)
  76. else:
  77. x = str(x)
  78. a = times.strftime("%Y-%m-%d") + " " + x + ":00:00"
  79. time_dict[t] = timezone.datetime.strptime(a, '%Y-%m-%d %H:%M:%S')
  80. t += 1
  81. return time_dict
  82. # 根据ip获取地址
  83. @staticmethod
  84. def getAddr(ip):
  85. base_dir = BASE_DIR
  86. # ip数据库
  87. db = IPIPDatabase(base_dir + '/DB/17monipdb.dat')
  88. addr = db.lookup(ip)
  89. ts = addr.split('\t')[0]
  90. return ts
  91. # 通过ip检索ipip指定信息 lang为CN或EN
  92. @staticmethod
  93. def getIpIpInfo(ip, lang, update=False):
  94. ipbd_dir = BASE_DIR + "/DB/mydata4vipday2.ipdb"
  95. db = ipdb.City(ipbd_dir)
  96. if update:
  97. rr = db.reload(ipbd_dir)
  98. info = db.find_map(ip, lang)
  99. return info
  100. @staticmethod
  101. def getUserID(userPhone='13800138000', getUser=True, setOTAID=False, μs=True):
  102. if μs == True:
  103. if getUser == True:
  104. timeID = str(round(time.time() * 1000000))
  105. userID = timeID + userPhone
  106. return userID
  107. else:
  108. if setOTAID == False:
  109. timeID = str(round(time.time() * 1000000))
  110. ID = userPhone + timeID
  111. return ID
  112. else:
  113. timeID = str(round(time.time() * 1000000))
  114. eID = '13800' + timeID + '138000'
  115. return eID
  116. else:
  117. if getUser == True:
  118. timeID = str(round(time.time() * 1000))
  119. userID = timeID + userPhone
  120. return userID
  121. else:
  122. if setOTAID == False:
  123. timeID = str(round(time.time() * 1000))
  124. ID = userPhone + timeID
  125. return ID
  126. else:
  127. timeID = str(round(time.time() * 1000))
  128. eID = '13800' + timeID + '138000'
  129. return eID
  130. # 生成随机数
  131. @staticmethod
  132. def RandomStr(randomlength=8, number=True):
  133. str = ''
  134. if number == False:
  135. characterSet = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsT' \
  136. 'tUuVvWwXxYyZz0123456789'
  137. else:
  138. characterSet = '0123456789'
  139. length = len(characterSet) - 1
  140. random = Random()
  141. for index in range(randomlength):
  142. str += characterSet[random.randint(0, length)]
  143. return str
  144. # 生成订单好
  145. @staticmethod
  146. def createOrderID():
  147. random_id = CommonService.RandomStr(6, True)
  148. order_id = datetime.datetime.now().strftime('%Y%m%d%H%M%S') + str(random_id)
  149. print('orderID:')
  150. print(order_id)
  151. return order_id
  152. # qs转换list datetime处理
  153. @staticmethod
  154. def qs_to_list(qs):
  155. res = []
  156. # print(qs)
  157. for ps in qs:
  158. try:
  159. if 'add_time' in ps:
  160. ps['add_time'] = ps['add_time'].strftime("%Y-%m-%d %H:%M:%S")
  161. if 'update_time' in ps:
  162. ps['update_time'] = ps['update_time'].strftime("%Y-%m-%d %H:%M:%S")
  163. if 'end_time' in ps:
  164. ps['end_time'] = ps['end_time'].strftime("%Y-%m-%d %H:%M:%S")
  165. if 'data_joined' in ps:
  166. if ps['data_joined']:
  167. ps['data_joined'] = ps['data_joined'].strftime("%Y-%m-%d %H:%M:%S")
  168. else:
  169. ps['data_joined'] = ''
  170. if 'userID__data_joined' in ps:
  171. if ps['userID__data_joined']:
  172. ps['userID__data_joined'] = ps['userID__data_joined'].strftime("%Y-%m-%d %H:%M:%S")
  173. else:
  174. ps['userID__data_joined'] = ''
  175. except Exception as e:
  176. pass
  177. res.append(ps)
  178. return res
  179. # 获取当前时间
  180. @staticmethod
  181. def get_now_time_str(n_time, tz):
  182. n_time = int(n_time)
  183. if tz:
  184. n_time = n_time + 3600 * float(tz)
  185. n_date = time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(int(n_time)))
  186. return n_date
  187. # 生成随机数
  188. @staticmethod
  189. def encrypt_data(randomlength=8, number=False):
  190. str = ''
  191. if number == False:
  192. characterSet = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsT' \
  193. 'tUuVvWwXxYyZz0123456789'
  194. else:
  195. characterSet = '0123456789'
  196. length = len(characterSet) - 1
  197. random = Random()
  198. for index in range(randomlength):
  199. str += characterSet[random.randint(0, length)]
  200. return str
  201. @staticmethod
  202. def updateMac(mac: str):
  203. macArray = mac.split(':')
  204. macArray[0] = int(macArray[0], 16)
  205. macArray[1] = int(macArray[1], 16)
  206. macArray[2] = int(macArray[2], 16)
  207. first = int(macArray[5], 16)
  208. second = int(macArray[4], 16)
  209. three = int(macArray[3], 16)
  210. # print(macArray)
  211. # print(first)
  212. # print(second)
  213. # print(three)
  214. if first == 255 and second == 255 and three == 255:
  215. return None
  216. first += 1
  217. if first / 256 == 1:
  218. second += 1
  219. first = first % 256
  220. if second / 256 == 1:
  221. three += 1
  222. second = second % 256
  223. macArray[3] = three
  224. macArray[4] = second
  225. macArray[5] = first
  226. # print(macArray)
  227. tmp = ':'.join(map(lambda x: "%02x" % x, macArray))
  228. # print(tmp)
  229. return tmp.upper()