CommonService.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  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
  240. #把格式化时间转换成时间戳
  241. @staticmethod
  242. def str_to_timestamp(str_time=None, format='%Y-%m-%d %H:%M:%S'):
  243. if str_time:
  244. time_tuple = time.strptime(str_time, format) # 把格式化好的时间转换成元祖
  245. result = time.mktime(time_tuple) # 把时间元祖转换成时间戳
  246. return int(result)
  247. return int(time.time())
  248. # 把时间戳转换成格式化
  249. @staticmethod
  250. def timestamp_to_str(timestamp=None, format='%Y-%m-%d %H:%M:%S'):
  251. if timestamp:
  252. time_tuple = time.localtime(timestamp) # 把时间戳转换成时间元祖
  253. result = time.strftime(format, time_tuple) # 把时间元祖转换成格式化好的时间
  254. return result
  255. else:
  256. return time.strptime(format)
  257. #计算N个月后的时间戳
  258. @staticmethod
  259. def calcMonthLater(addMonth, unix_timestamp=None):
  260. if unix_timestamp:
  261. now_year = time.localtime(unix_timestamp).tm_year
  262. now_month = time.localtime(unix_timestamp).tm_mon
  263. now_day = time.localtime(unix_timestamp).tm_mday
  264. now_hour = time.localtime(unix_timestamp).tm_hour
  265. now_min = time.localtime(unix_timestamp).tm_min
  266. now_second = time.localtime(unix_timestamp).tm_sec
  267. else:
  268. now_year = datetime.datetime.now().year
  269. now_month = datetime.datetime.now().month
  270. now_day = datetime.datetime.now().day
  271. now_hour = datetime.datetime.now().hour
  272. now_min = datetime.datetime.now().minute
  273. now_second = datetime.datetime.now().second
  274. for add in range(addMonth):
  275. if now_month == 12:
  276. now_year += 1
  277. now_month = 1
  278. else:
  279. now_month += 1
  280. for is_format in range(4):
  281. try:
  282. date_format = '{now_year}-{now_month}-{now_day} {now_hour}:{now_min}:{now_second}' \
  283. .format(now_year=now_year,now_month=now_month,now_day=now_day,now_hour=now_hour,
  284. now_min=now_min,now_second=now_second)
  285. timestamps = CommonService.str_to_timestamp(date_format)
  286. except Exception as e:
  287. if str(e) == 'day is out of range for month':
  288. now_day = now_day - 1
  289. return timestamps
  290. @staticmethod
  291. def updateMac(mac: str):
  292. macArray = mac.split(':')
  293. macArray[0] = int(macArray[0], 16)
  294. macArray[1] = int(macArray[1], 16)
  295. macArray[2] = int(macArray[2], 16)
  296. first = int(macArray[5], 16)
  297. second = int(macArray[4], 16)
  298. three = int(macArray[3], 16)
  299. # print(macArray)
  300. # print(first)
  301. # print(second)
  302. # print(three)
  303. if first == 255 and second == 255 and three == 255:
  304. return None
  305. first += 1
  306. if first / 256 == 1:
  307. second += 1
  308. first = first % 256
  309. if second / 256 == 1:
  310. three += 1
  311. second = second % 256
  312. macArray[3] = three
  313. macArray[4] = second
  314. macArray[5] = first
  315. # print(macArray)
  316. tmp = ':'.join(map(lambda x: "%02x" % x, macArray))
  317. # print(tmp)
  318. return tmp.upper()
  319. @staticmethod
  320. def decode_data(content, start=1, end=4):
  321. try:
  322. for i in range(start, end):
  323. if i == 1:
  324. content = base64.b64decode(content)
  325. content = content.decode('utf-8')
  326. content = content[1:-1]
  327. if i == 2:
  328. content = base64.b64decode(content)
  329. content = content.decode('utf-8')
  330. content = content[2:-2]
  331. if i == 3:
  332. content = base64.b64decode(content)
  333. content = content.decode('utf-8')
  334. content = content[3:-3]
  335. print(content)
  336. return content
  337. except Exception as e:
  338. print(e)
  339. return None
  340. @staticmethod
  341. def encode_data(content, start=1, end=4):
  342. for i in range(start, end):
  343. if i == 1:
  344. content = CommonService.RandomStr(3, False) + content + CommonService.RandomStr(3, False)
  345. content = base64.b64encode(str(content).encode("utf-8")).decode('utf8')
  346. if i == 2:
  347. content = CommonService.RandomStr(2, False) + str(content) + CommonService.RandomStr(2, False)
  348. content = base64.b64encode(str(content).encode("utf-8")).decode('utf8')
  349. if i == 3:
  350. content = CommonService.RandomStr(1, False) + str(content) + CommonService.RandomStr(1, False)
  351. content = base64.b64encode(str(content).encode("utf-8")).decode('utf8')
  352. return content
  353. @staticmethod
  354. def encode_data_without_salt(content):
  355. return base64.b64encode(str(content).encode("utf-8")).decode('utf8')