CommonService.py 9.0 KB

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