CommonService.py 14 KB

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