CommonService.py 8.3 KB

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