CommonService.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  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. # 格式化query_set转dict
  34. @staticmethod
  35. def request_dict_to_dict(request_dict):
  36. # 传参格式转换,键包含meta获取meta[]中的值,值'true'/'false'转为True,False
  37. key_list = []
  38. value_list = []
  39. for k, v in request_dict.items():
  40. key_list.append(k[k.index('[')+1:k.index(']')] if 'meta' in k else k)
  41. if v == 'true':
  42. v = True
  43. elif v == 'false':
  44. v = False
  45. value_list.append(v)
  46. data_dict = dict(zip(key_list, value_list))
  47. print(data_dict)
  48. return data_dict
  49. # 获取文件大小
  50. @staticmethod
  51. def get_file_size(file_path='', suffix_type='', decimal_point=0):
  52. # for x in ['bytes', 'KB', 'MB', 'GB', 'TB']:
  53. # path = Path() / 'D:/TestServer/123444.mp4'
  54. path = Path() / file_path
  55. size = path.stat().st_size
  56. mb_size = 0.0
  57. if suffix_type == 'MB':
  58. mb_size = size / 1024.0 / 1024.0
  59. if decimal_point != 0:
  60. mb_size = round(mb_size, decimal_point)
  61. return mb_size
  62. @staticmethod
  63. def get_param_flag(data=[]):
  64. # print(data)
  65. flag = True
  66. for v in data:
  67. if v is None:
  68. flag = False
  69. break
  70. return flag
  71. @staticmethod
  72. def get_ip_address(request):
  73. """
  74. 获取ip地址
  75. :param request:
  76. :return:
  77. """
  78. try:
  79. real_ip = request.META['HTTP_X_FORWARDED_FOR']
  80. clientIP = real_ip.split(",")[0]
  81. except:
  82. try:
  83. clientIP = request.META['REMOTE_ADDR']
  84. except Exception as e:
  85. clientIP = ''
  86. return clientIP
  87. # @获取一天每个小时的datetime.datetime
  88. @staticmethod
  89. def getTimeDict(times):
  90. time_dict = {}
  91. t = 0
  92. for x in range(24):
  93. if x < 10:
  94. x = '0' + str(x)
  95. else:
  96. x = str(x)
  97. a = times.strftime("%Y-%m-%d") + " " + x + ":00:00"
  98. time_dict[t] = timezone.datetime.strptime(a, '%Y-%m-%d %H:%M:%S')
  99. t += 1
  100. return time_dict
  101. # 根据ip获取地址
  102. @staticmethod
  103. def getAddr(ip):
  104. print('start_time=' + str(time.time()))
  105. base_dir = BASE_DIR
  106. # ip数据库
  107. db = IPIPDatabase(base_dir + '/DB/17monipdb.dat')
  108. addr = db.lookup(ip)
  109. # ModelService.add_tmp_log(addr)
  110. ts = addr.split('\t')[0]
  111. print('end_time=' + str(time.time()))
  112. return ts
  113. # 通过ip检索ipip指定信息 lang为CN或EN
  114. @staticmethod
  115. def getIpIpInfo(ip, lang, update=False):
  116. ipbd_dir = BASE_DIR + "/DB/mydata4vipday2.ipdb"
  117. db = ipdb.City(ipbd_dir)
  118. if update:
  119. rr = db.reload(ipbd_dir)
  120. info = db.find_map(ip, lang)
  121. return info
  122. @staticmethod
  123. def getUserID(userPhone='13800138000', getUser=True, setOTAID=False, μs=True):
  124. if μs == True:
  125. if getUser == True:
  126. timeID = str(round(time.time() * 1000000))
  127. userID = timeID + userPhone
  128. return userID
  129. else:
  130. if setOTAID == False:
  131. timeID = str(round(time.time() * 1000000))
  132. ID = userPhone + timeID
  133. return ID
  134. else:
  135. timeID = str(round(time.time() * 1000000))
  136. eID = '13800' + timeID + '138000'
  137. return eID
  138. else:
  139. if getUser == True:
  140. timeID = str(round(time.time() * 1000))
  141. userID = timeID + userPhone
  142. return userID
  143. else:
  144. if setOTAID == False:
  145. timeID = str(round(time.time() * 1000))
  146. ID = userPhone + timeID
  147. return ID
  148. else:
  149. timeID = str(round(time.time() * 1000))
  150. eID = '13800' + timeID + '138000'
  151. return eID
  152. # 生成随机数
  153. @staticmethod
  154. def RandomStr(randomlength=8, number=True):
  155. str = ''
  156. if number == False:
  157. characterSet = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsT' \
  158. 'tUuVvWwXxYyZz0123456789'
  159. else:
  160. characterSet = '0123456789'
  161. length = len(characterSet) - 1
  162. random = Random()
  163. for index in range(randomlength):
  164. str += characterSet[random.randint(0, length)]
  165. return str
  166. # 生成订单好
  167. @staticmethod
  168. def createOrderID():
  169. random_id = CommonService.RandomStr(6, True)
  170. order_id = datetime.datetime.now().strftime('%Y%m%d%H%M%S') + str(random_id)
  171. print('orderID:')
  172. print(order_id)
  173. return order_id
  174. # qs转换list datetime处理
  175. @staticmethod
  176. def qs_to_list(qs):
  177. res = []
  178. # print(qs)
  179. for ps in qs:
  180. try:
  181. if 'add_time' in ps:
  182. ps['add_time'] = ps['add_time'].strftime("%Y-%m-%d %H:%M:%S")
  183. if 'update_time' in ps:
  184. ps['update_time'] = ps['update_time'].strftime("%Y-%m-%d %H:%M:%S")
  185. if 'end_time' in ps:
  186. ps['end_time'] = ps['end_time'].strftime("%Y-%m-%d %H:%M:%S")
  187. if 'data_joined' in ps:
  188. if ps['data_joined']:
  189. ps['data_joined'] = ps['data_joined'].strftime("%Y-%m-%d %H:%M:%S")
  190. else:
  191. ps['data_joined'] = ''
  192. if 'userID__data_joined' in ps:
  193. if ps['userID__data_joined']:
  194. ps['userID__data_joined'] = ps['userID__data_joined'].strftime("%Y-%m-%d %H:%M:%S")
  195. else:
  196. ps['userID__data_joined'] = ''
  197. except Exception as e:
  198. pass
  199. res.append(ps)
  200. return res
  201. # 获取当前时间
  202. @staticmethod
  203. def get_now_time_str(n_time, tz, lang):
  204. print(n_time)
  205. print(tz)
  206. print(lang)
  207. n_time = int(n_time) + 3600 * float(tz)
  208. if lang == 'cn':
  209. return time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(int(n_time)))
  210. else:
  211. return time.strftime('%m-%d-%Y %H:%M:%S', time.gmtime(int(n_time)))
  212. # 生成随机数
  213. @staticmethod
  214. def encrypt_data(randomlength=8, number=False):
  215. str = ''
  216. if number == False:
  217. characterSet = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsT' \
  218. 'tUuVvWwXxYyZz0123456789'
  219. else:
  220. characterSet = '0123456789'
  221. length = len(characterSet) - 1
  222. random = Random()
  223. for index in range(randomlength):
  224. str += characterSet[random.randint(0, length)]
  225. return str
  226. @staticmethod
  227. def decode_data(content, start=1, end=4):
  228. try:
  229. for i in range(start, end):
  230. if i == 1:
  231. content = base64.b64decode(content)
  232. content = content.decode('utf-8')
  233. content = content[1:-1]
  234. if i == 2:
  235. content = base64.b64decode(content)
  236. content = content.decode('utf-8')
  237. content = content[2:-2]
  238. if i == 3:
  239. content = base64.b64decode(content)
  240. content = content.decode('utf-8')
  241. content = content[3:-3]
  242. return content
  243. except Exception as e:
  244. print(e)
  245. return None
  246. @staticmethod
  247. def encode_data(content, start=1, end=4):
  248. for i in range(start, end):
  249. if i == 1:
  250. content = RandomStr(3, False)+content+RandomStr(3, False)
  251. content = base64.b64encode(str(content).encode("utf-8")).decode('utf8')
  252. if i == 2:
  253. content = RandomStr(2, False)+str(content)+RandomStr(2, False)
  254. content = base64.b64encode(str(content).encode("utf-8")).decode('utf8')
  255. if i == 3:
  256. content = RandomStr(1, False)+str(content)+RandomStr(1, False)
  257. content = base64.b64encode(str(content).encode("utf-8")).decode('utf8')
  258. return content
  259. #把格式化时间转换成时间戳
  260. @staticmethod
  261. def str_to_timestamp(str_time=None, format='%Y-%m-%d %H:%M:%S'):
  262. if str_time:
  263. time_tuple = time.strptime(str_time, format) # 把格式化好的时间转换成元祖
  264. result = time.mktime(time_tuple) # 把时间元祖转换成时间戳
  265. return int(result)
  266. return int(time.time())
  267. # 把时间戳转换成格式化
  268. @staticmethod
  269. def timestamp_to_str(timestamp=None, format='%Y-%m-%d %H:%M:%S'):
  270. if timestamp:
  271. time_tuple = time.localtime(timestamp) # 把时间戳转换成时间元祖
  272. result = time.strftime(format, time_tuple) # 把时间元祖转换成格式化好的时间
  273. return result
  274. else:
  275. return time.strptime(format)
  276. #计算N个月后的时间戳
  277. @staticmethod
  278. def calcMonthLater(addMonth, unix_timestamp=None):
  279. if unix_timestamp:
  280. now_year = time.localtime(unix_timestamp).tm_year
  281. now_month = time.localtime(unix_timestamp).tm_mon
  282. now_day = time.localtime(unix_timestamp).tm_mday
  283. now_hour = time.localtime(unix_timestamp).tm_hour
  284. now_min = time.localtime(unix_timestamp).tm_min
  285. now_second = time.localtime(unix_timestamp).tm_sec
  286. else:
  287. now_year = datetime.datetime.now().year
  288. now_month = datetime.datetime.now().month
  289. now_day = datetime.datetime.now().day
  290. now_hour = datetime.datetime.now().hour
  291. now_min = datetime.datetime.now().minute
  292. now_second = datetime.datetime.now().second
  293. for add in range(addMonth):
  294. if now_month == 12:
  295. now_year += 1
  296. now_month = 1
  297. else:
  298. now_month += 1
  299. for is_format in range(4):
  300. try:
  301. date_format = '{now_year}-{now_month}-{now_day} {now_hour}:{now_min}:{now_second}' \
  302. .format(now_year=now_year,now_month=now_month,now_day=now_day,now_hour=now_hour,
  303. now_min=now_min,now_second=now_second)
  304. timestamps = CommonService.str_to_timestamp(date_format)
  305. except Exception as e:
  306. if str(e) == 'day is out of range for month':
  307. now_day = now_day - 1
  308. return timestamps
  309. @staticmethod
  310. def updateMac(mac: str):
  311. macArray = mac.split(':')
  312. macArray[0] = int(macArray[0], 16)
  313. macArray[1] = int(macArray[1], 16)
  314. macArray[2] = int(macArray[2], 16)
  315. first = int(macArray[5], 16)
  316. second = int(macArray[4], 16)
  317. three = int(macArray[3], 16)
  318. # print(macArray)
  319. # print(first)
  320. # print(second)
  321. # print(three)
  322. if first == 255 and second == 255 and three == 255:
  323. return None
  324. first += 1
  325. if first / 256 == 1:
  326. second += 1
  327. first = first % 256
  328. if second / 256 == 1:
  329. three += 1
  330. second = second % 256
  331. macArray[3] = three
  332. macArray[4] = second
  333. macArray[5] = first
  334. # print(macArray)
  335. tmp = ':'.join(map(lambda x: "%02x" % x, macArray))
  336. # print(tmp)
  337. return tmp.upper()
  338. @staticmethod
  339. def decode_data(content, start=1, end=4):
  340. try:
  341. for i in range(start, end):
  342. if i == 1:
  343. content = base64.b64decode(content)
  344. content = content.decode('utf-8')
  345. content = content[1:-1]
  346. if i == 2:
  347. content = base64.b64decode(content)
  348. content = content.decode('utf-8')
  349. content = content[2:-2]
  350. if i == 3:
  351. content = base64.b64decode(content)
  352. content = content.decode('utf-8')
  353. content = content[3:-3]
  354. print(content)
  355. return content
  356. except Exception as e:
  357. print(e)
  358. return None
  359. @staticmethod
  360. def encode_data(content, start=1, end=4):
  361. for i in range(start, end):
  362. if i == 1:
  363. content = CommonService.RandomStr(3, False) + content + CommonService.RandomStr(3, False)
  364. content = base64.b64encode(str(content).encode("utf-8")).decode('utf8')
  365. if i == 2:
  366. content = CommonService.RandomStr(2, False) + str(content) + CommonService.RandomStr(2, False)
  367. content = base64.b64encode(str(content).encode("utf-8")).decode('utf8')
  368. if i == 3:
  369. content = CommonService.RandomStr(1, False) + str(content) + CommonService.RandomStr(1, False)
  370. content = base64.b64encode(str(content).encode("utf-8")).decode('utf8')
  371. return content
  372. @staticmethod
  373. def encode_data_without_salt(content):
  374. return base64.b64encode(str(content).encode("utf-8")).decode('utf8')