CommonService.py 8.3 KB

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