CommonService.py 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  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. print('start_time=' + str(time.time()))
  89. base_dir = BASE_DIR
  90. # ip数据库
  91. db = IPIPDatabase(base_dir + '/DB/17monipdb.dat')
  92. addr = db.lookup(ip)
  93. # ModelService.add_tmp_log(addr)
  94. ts = addr.split('\t')[0]
  95. print('end_time=' + str(time.time()))
  96. return ts
  97. # 通过ip检索ipip指定信息 lang为CN或EN
  98. @staticmethod
  99. def getIpIpInfo(ip, lang, update=False):
  100. ipbd_dir = BASE_DIR + "/DB/mydata4vipday2.ipdb"
  101. db = ipdb.City(ipbd_dir)
  102. if update:
  103. rr = db.reload(ipbd_dir)
  104. info = db.find_map(ip, lang)
  105. return info
  106. @staticmethod
  107. def getUserID(userPhone='13800138000', getUser=True, setOTAID=False, μs=True):
  108. if μs == True:
  109. if getUser == True:
  110. timeID = str(round(time.time() * 1000000))
  111. userID = timeID + userPhone
  112. return userID
  113. else:
  114. if setOTAID == False:
  115. timeID = str(round(time.time() * 1000000))
  116. ID = userPhone + timeID
  117. return ID
  118. else:
  119. timeID = str(round(time.time() * 1000000))
  120. eID = '13800' + timeID + '138000'
  121. return eID
  122. else:
  123. if getUser == True:
  124. timeID = str(round(time.time() * 1000))
  125. userID = timeID + userPhone
  126. return userID
  127. else:
  128. if setOTAID == False:
  129. timeID = str(round(time.time() * 1000))
  130. ID = userPhone + timeID
  131. return ID
  132. else:
  133. timeID = str(round(time.time() * 1000))
  134. eID = '13800' + timeID + '138000'
  135. return eID
  136. # 生成随机数
  137. @staticmethod
  138. def RandomStr(randomlength=8, number=True):
  139. str = ''
  140. if number == False:
  141. characterSet = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsT' \
  142. 'tUuVvWwXxYyZz0123456789'
  143. else:
  144. characterSet = '0123456789'
  145. length = len(characterSet) - 1
  146. random = Random()
  147. for index in range(randomlength):
  148. str += characterSet[random.randint(0, length)]
  149. return str
  150. # 生成订单好
  151. @staticmethod
  152. def createOrderID():
  153. random_id = CommonService.RandomStr(6, True)
  154. order_id = datetime.datetime.now().strftime('%Y%m%d%H%M%S') + str(random_id)
  155. print('orderID:')
  156. print(order_id)
  157. return order_id
  158. # qs转换list datetime处理
  159. @staticmethod
  160. def qs_to_list(qs):
  161. res = []
  162. # print(qs)
  163. for ps in qs:
  164. try:
  165. if 'add_time' in ps:
  166. ps['add_time'] = ps['add_time'].strftime("%Y-%m-%d %H:%M:%S")
  167. if 'update_time' in ps:
  168. ps['update_time'] = ps['update_time'].strftime("%Y-%m-%d %H:%M:%S")
  169. if 'end_time' in ps:
  170. ps['end_time'] = ps['end_time'].strftime("%Y-%m-%d %H:%M:%S")
  171. if 'data_joined' in ps:
  172. if ps['data_joined']:
  173. ps['data_joined'] = ps['data_joined'].strftime("%Y-%m-%d %H:%M:%S")
  174. else:
  175. ps['data_joined'] = ''
  176. if 'userID__data_joined' in ps:
  177. if ps['userID__data_joined']:
  178. ps['userID__data_joined'] = ps['userID__data_joined'].strftime("%Y-%m-%d %H:%M:%S")
  179. else:
  180. ps['userID__data_joined'] = ''
  181. except Exception as e:
  182. pass
  183. res.append(ps)
  184. return res
  185. # 获取当前时间
  186. @staticmethod
  187. def get_now_time_str(n_time, tz):
  188. n_time = int(n_time)
  189. if tz:
  190. n_time = n_time + 3600 * float(tz)
  191. n_date = time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(int(n_time)))
  192. return n_date
  193. # 生成随机数
  194. @staticmethod
  195. def encrypt_data(randomlength=8, number=False):
  196. str = ''
  197. if number == False:
  198. characterSet = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsT' \
  199. 'tUuVvWwXxYyZz0123456789'
  200. else:
  201. characterSet = '0123456789'
  202. length = len(characterSet) - 1
  203. random = Random()
  204. for index in range(randomlength):
  205. str += characterSet[random.randint(0, length)]
  206. return str
  207. @staticmethod
  208. def decode_data(content, start=1, end=4):
  209. try:
  210. for i in range(start, end):
  211. if i == 1:
  212. content = base64.b64decode(content)
  213. content = content.decode('utf-8')
  214. content = content[1:-1]
  215. if i == 2:
  216. content = base64.b64decode(content)
  217. content = content.decode('utf-8')
  218. content = content[2:-2]
  219. if i == 3:
  220. content = base64.b64decode(content)
  221. content = content.decode('utf-8')
  222. content = content[3:-3]
  223. return content
  224. except Exception as e:
  225. print(e)
  226. return None
  227. @staticmethod
  228. def encode_data(content, start=1, end=4):
  229. for i in range(start, end):
  230. if i == 1:
  231. content = RandomStr(3, False)+content+RandomStr(3, False)
  232. content = base64.b64encode(str(content).encode("utf-8")).decode('utf8')
  233. if i == 2:
  234. content = RandomStr(2, False)+str(content)+RandomStr(2, False)
  235. content = base64.b64encode(str(content).encode("utf-8")).decode('utf8')
  236. if i == 3:
  237. content = RandomStr(1, False)+str(content)+RandomStr(1, False)
  238. content = base64.b64encode(str(content).encode("utf-8")).decode('utf8')
  239. return content