CommonService.py 8.4 KB

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