CommonService.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  1. # -*- coding: utf-8 -*-
  2. # 高复用性函数封装到CommonService类
  3. import base64
  4. import datetime
  5. import time
  6. from pathlib import Path
  7. from random import Random
  8. import ipdb
  9. import simplejson as json
  10. from django.core import serializers
  11. from django.utils import timezone
  12. from pyipip import IPIPDatabase
  13. from Ansjer.config import BASE_DIR, UNICODE_ASCII_CHARACTER_SET
  14. import OpenSSL.crypto as ct
  15. from base64 import encodebytes
  16. from Controller.CheckUserData import RandomStr
  17. from Service.ModelService import ModelService
  18. class CommonService:
  19. # 添加模糊搜索
  20. @staticmethod
  21. def get_kwargs(data={}):
  22. kwargs = {}
  23. for (k, v) in data.items():
  24. if v is not None and v != u'':
  25. kwargs[k + '__icontains'] = v
  26. return kwargs
  27. # 定义静态方法
  28. # 格式化query_set转dict
  29. @staticmethod
  30. def qs_to_dict(query_set):
  31. sqlJSON = serializers.serialize('json', query_set)
  32. sqlList = json.loads(sqlJSON)
  33. sqlDict = dict(zip(["datas"], [sqlList]))
  34. return sqlDict
  35. # 格式化query_set转dict
  36. @staticmethod
  37. def request_dict_to_dict(request_dict):
  38. # 传参格式转换,键包含meta获取meta[]中的值,值'true'/'false'转为True,False
  39. key_list = []
  40. value_list = []
  41. for k, v in request_dict.items():
  42. key_list.append(k[k.index('[')+1:k.index(']')] if 'meta' in k else k)
  43. if v == 'true':
  44. v = True
  45. elif v == 'false':
  46. v = False
  47. value_list.append(v)
  48. data_dict = dict(zip(key_list, value_list))
  49. print(data_dict)
  50. return data_dict
  51. # 获取文件大小
  52. @staticmethod
  53. def get_file_size(file_path='', suffix_type='', decimal_point=0):
  54. # for x in ['bytes', 'KB', 'MB', 'GB', 'TB']:
  55. # path = Path() / 'D:/TestServer/123444.mp4'
  56. path = Path() / file_path
  57. size = path.stat().st_size
  58. mb_size = 0.0
  59. if suffix_type == 'MB':
  60. mb_size = size / 1024.0 / 1024.0
  61. if decimal_point != 0:
  62. mb_size = round(mb_size, decimal_point)
  63. return mb_size
  64. @staticmethod
  65. def get_param_flag(data=[]):
  66. # print(data)
  67. flag = True
  68. for v in data:
  69. if v is None:
  70. flag = False
  71. break
  72. return flag
  73. @staticmethod
  74. def get_ip_address(request):
  75. """
  76. 获取ip地址
  77. :param request:
  78. :return:
  79. """
  80. try:
  81. real_ip = request.META['HTTP_X_FORWARDED_FOR']
  82. clientIP = real_ip.split(",")[0]
  83. except:
  84. try:
  85. clientIP = request.META['REMOTE_ADDR']
  86. except Exception as e:
  87. clientIP = ''
  88. return clientIP
  89. # @获取一天每个小时的datetime.datetime
  90. @staticmethod
  91. def getTimeDict(times):
  92. time_dict = {}
  93. t = 0
  94. for x in range(24):
  95. if x < 10:
  96. x = '0' + str(x)
  97. else:
  98. x = str(x)
  99. a = times.strftime("%Y-%m-%d") + " " + x + ":00:00"
  100. time_dict[t] = timezone.datetime.strptime(a, '%Y-%m-%d %H:%M:%S')
  101. t += 1
  102. return time_dict
  103. # 根据ip获取地址
  104. @staticmethod
  105. def getAddr(ip):
  106. print('start_time=' + str(time.time()))
  107. base_dir = BASE_DIR
  108. # ip数据库
  109. db = IPIPDatabase(base_dir + '/DB/17monipdb.dat')
  110. addr = db.lookup(ip)
  111. # ModelService.add_tmp_log(addr)
  112. ts = addr.split('\t')[0]
  113. print('end_time=' + str(time.time()))
  114. return ts
  115. # 通过ip检索ipip指定信息 lang为CN或EN
  116. @staticmethod
  117. def getIpIpInfo(ip, lang, update=False):
  118. ipbd_dir = BASE_DIR + "/DB/mydata4vipday2.ipdb"
  119. db = ipdb.City(ipbd_dir)
  120. if update:
  121. rr = db.reload(ipbd_dir)
  122. info = db.find_map(ip, lang)
  123. return info
  124. @staticmethod
  125. def getUserID(userPhone='13800138000', getUser=True, setOTAID=False, μs=True):
  126. if μs == True:
  127. if getUser == True:
  128. timeID = str(round(time.time() * 1000000))
  129. userID = timeID + userPhone
  130. return userID
  131. else:
  132. if setOTAID == False:
  133. timeID = str(round(time.time() * 1000000))
  134. ID = userPhone + timeID
  135. return ID
  136. else:
  137. timeID = str(round(time.time() * 1000000))
  138. eID = '13800' + timeID + '138000'
  139. return eID
  140. else:
  141. if getUser == True:
  142. timeID = str(round(time.time() * 1000))
  143. userID = timeID + userPhone
  144. return userID
  145. else:
  146. if setOTAID == False:
  147. timeID = str(round(time.time() * 1000))
  148. ID = userPhone + timeID
  149. return ID
  150. else:
  151. timeID = str(round(time.time() * 1000))
  152. eID = '13800' + timeID + '138000'
  153. return eID
  154. # 生成随机数
  155. @staticmethod
  156. def RandomStr(randomlength=8, number=True):
  157. str = ''
  158. if number == False:
  159. characterSet = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsT' \
  160. 'tUuVvWwXxYyZz0123456789'
  161. else:
  162. characterSet = '0123456789'
  163. length = len(characterSet) - 1
  164. random = Random()
  165. for index in range(randomlength):
  166. str += characterSet[random.randint(0, length)]
  167. return str
  168. # 生成订单好
  169. @staticmethod
  170. def createOrderID():
  171. random_id = CommonService.RandomStr(6, True)
  172. order_id = datetime.datetime.now().strftime('%Y%m%d%H%M%S') + str(random_id)
  173. print('orderID:')
  174. print(order_id)
  175. return order_id
  176. # qs转换list datetime处理
  177. @staticmethod
  178. def qs_to_list(qs):
  179. res = []
  180. # print(qs)
  181. for ps in qs:
  182. try:
  183. if 'time' in ps:
  184. ps['time'] = ps['time'].strftime("%Y-%m-%d %H:%M:%S")
  185. if 'add_time' in ps:
  186. ps['add_time'] = ps['add_time'].strftime("%Y-%m-%d %H:%M:%S")
  187. if 'update_time' in ps:
  188. ps['update_time'] = ps['update_time'].strftime("%Y-%m-%d %H:%M:%S")
  189. if 'end_time' in ps:
  190. ps['end_time'] = ps['end_time'].strftime("%Y-%m-%d %H:%M:%S")
  191. if 'data_joined' in ps:
  192. if ps['data_joined']:
  193. ps['data_joined'] = ps['data_joined'].strftime("%Y-%m-%d %H:%M:%S")
  194. else:
  195. ps['data_joined'] = ''
  196. if 'userID__data_joined' in ps:
  197. if ps['userID__data_joined']:
  198. ps['userID__data_joined'] = ps['userID__data_joined'].strftime("%Y-%m-%d %H:%M:%S")
  199. else:
  200. ps['userID__data_joined'] = ''
  201. except Exception as e:
  202. pass
  203. res.append(ps)
  204. return res
  205. # 获取当前时间
  206. @staticmethod
  207. def get_now_time_str(n_time, tz, lang):
  208. print(n_time)
  209. print(tz)
  210. print(lang)
  211. n_time = int(n_time) + 3600 * float(tz)
  212. if lang == 'cn':
  213. return time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(int(n_time)))
  214. else:
  215. return time.strftime('%m-%d-%Y %H:%M:%S', time.gmtime(int(n_time)))
  216. # 生成随机数
  217. @staticmethod
  218. def encrypt_data(randomlength=8, number=False):
  219. str = ''
  220. if number == False:
  221. characterSet = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsT' \
  222. 'tUuVvWwXxYyZz0123456789'
  223. else:
  224. characterSet = '0123456789'
  225. length = len(characterSet) - 1
  226. random = Random()
  227. for index in range(randomlength):
  228. str += characterSet[random.randint(0, length)]
  229. return str
  230. @staticmethod
  231. def decode_data(content, start=1, end=4):
  232. if not content:
  233. return ''
  234. try:
  235. for i in range(start, end):
  236. if i == 1:
  237. content = base64.b64decode(content)
  238. content = content.decode('utf-8')
  239. content = content[1:-1]
  240. if i == 2:
  241. content = base64.b64decode(content)
  242. content = content.decode('utf-8')
  243. content = content[2:-2]
  244. if i == 3:
  245. content = base64.b64decode(content)
  246. content = content.decode('utf-8')
  247. content = content[3:-3]
  248. return content
  249. except Exception as e:
  250. print(e)
  251. return None
  252. @staticmethod
  253. def encode_data(content, start=1, end=4):
  254. if not content:
  255. return ''
  256. for i in range(start, end):
  257. if i == 1:
  258. content = RandomStr(3, False)+content+RandomStr(3, False)
  259. content = base64.b64encode(str(content).encode("utf-8")).decode('utf8')
  260. if i == 2:
  261. content = RandomStr(2, False)+str(content)+RandomStr(2, False)
  262. content = base64.b64encode(str(content).encode("utf-8")).decode('utf8')
  263. if i == 3:
  264. content = RandomStr(1, False)+str(content)+RandomStr(1, False)
  265. content = base64.b64encode(str(content).encode("utf-8")).decode('utf8')
  266. return content
  267. #把格式化时间转换成时间戳
  268. @staticmethod
  269. def str_to_timestamp(str_time=None, format='%Y-%m-%d %H:%M:%S'):
  270. if str_time:
  271. time_tuple = time.strptime(str_time, format) # 把格式化好的时间转换成元祖
  272. result = time.mktime(time_tuple) # 把时间元祖转换成时间戳
  273. return int(result)
  274. return int(time.time())
  275. # 把时间戳转换成格式化
  276. @staticmethod
  277. def timestamp_to_str(timestamp=None, format='%Y-%m-%d %H:%M:%S'):
  278. if timestamp:
  279. time_tuple = time.localtime(timestamp) # 把时间戳转换成时间元祖
  280. result = time.strftime(format, time_tuple) # 把时间元祖转换成格式化好的时间
  281. return result
  282. else:
  283. return time.strptime(format)
  284. #计算N个月后的时间戳
  285. @staticmethod
  286. def calcMonthLater(addMonth, unix_timestamp=None):
  287. if unix_timestamp:
  288. now_year = time.localtime(unix_timestamp).tm_year
  289. now_month = time.localtime(unix_timestamp).tm_mon
  290. now_day = time.localtime(unix_timestamp).tm_mday
  291. now_hour = time.localtime(unix_timestamp).tm_hour
  292. now_min = time.localtime(unix_timestamp).tm_min
  293. now_second = time.localtime(unix_timestamp).tm_sec
  294. else:
  295. now_year = datetime.datetime.now().year
  296. now_month = datetime.datetime.now().month
  297. now_day = datetime.datetime.now().day
  298. now_hour = datetime.datetime.now().hour
  299. now_min = datetime.datetime.now().minute
  300. now_second = datetime.datetime.now().second
  301. for add in range(addMonth):
  302. if now_month == 12:
  303. now_year += 1
  304. now_month = 1
  305. else:
  306. now_month += 1
  307. for is_format in range(4):
  308. try:
  309. date_format = '{now_year}-{now_month}-{now_day} {now_hour}:{now_min}:{now_second}' \
  310. .format(now_year=now_year,now_month=now_month,now_day=now_day,now_hour=now_hour,
  311. now_min=now_min,now_second=now_second)
  312. timestamps = CommonService.str_to_timestamp(date_format)
  313. except Exception as e:
  314. if str(e) == 'day is out of range for month':
  315. now_day = now_day - 1
  316. return timestamps
  317. @staticmethod
  318. def updateMac(mac: str):
  319. macArray = mac.split(':')
  320. macArray[0] = int(macArray[0], 16)
  321. macArray[1] = int(macArray[1], 16)
  322. macArray[2] = int(macArray[2], 16)
  323. first = int(macArray[5], 16)
  324. second = int(macArray[4], 16)
  325. three = int(macArray[3], 16)
  326. # print(macArray)
  327. # print(first)
  328. # print(second)
  329. # print(three)
  330. if first == 255 and second == 255 and three == 255:
  331. return None
  332. first += 1
  333. if first / 256 == 1:
  334. second += 1
  335. first = first % 256
  336. if second / 256 == 1:
  337. three += 1
  338. second = second % 256
  339. macArray[3] = three
  340. macArray[4] = second
  341. macArray[5] = first
  342. # print(macArray)
  343. tmp = ':'.join(map(lambda x: "%02x" % x, macArray))
  344. # print(tmp)
  345. return tmp.upper()
  346. @staticmethod
  347. def decode_data(content, start=1, end=4):
  348. if not content:
  349. return ''
  350. try:
  351. for i in range(start, end):
  352. if i == 1:
  353. content = base64.b64decode(content)
  354. content = content.decode('utf-8')
  355. content = content[1:-1]
  356. if i == 2:
  357. content = base64.b64decode(content)
  358. content = content.decode('utf-8')
  359. content = content[2:-2]
  360. if i == 3:
  361. content = base64.b64decode(content)
  362. content = content.decode('utf-8')
  363. content = content[3:-3]
  364. print(content)
  365. return content
  366. except Exception as e:
  367. print(e)
  368. return None
  369. @staticmethod
  370. def encode_data(content, start=1, end=4):
  371. if not content:
  372. return ''
  373. for i in range(start, end):
  374. if i == 1:
  375. content = CommonService.RandomStr(3, False) + content + CommonService.RandomStr(3, False)
  376. content = base64.b64encode(str(content).encode("utf-8")).decode('utf8')
  377. if i == 2:
  378. content = CommonService.RandomStr(2, False) + str(content) + CommonService.RandomStr(2, False)
  379. content = base64.b64encode(str(content).encode("utf-8")).decode('utf8')
  380. if i == 3:
  381. content = CommonService.RandomStr(1, False) + str(content) + CommonService.RandomStr(1, False)
  382. content = base64.b64encode(str(content).encode("utf-8")).decode('utf8')
  383. return content
  384. @staticmethod
  385. def encode_data_without_salt(content):
  386. return base64.b64encode(str(content).encode("utf-8")).decode('utf8')
  387. @staticmethod
  388. def check_time_stamp_token(token, time_stamp):
  389. # 时间戳token校验
  390. if not all([token, time_stamp]):
  391. return False
  392. try:
  393. token = int(CommonService.decode_data(token))
  394. time_stamp = int(time_stamp)
  395. now_time = int(time.time())
  396. distance = now_time - time_stamp
  397. if token != time_stamp or distance > 60000 or distance < -60000: # 为了全球化时间控制在一天内
  398. return False
  399. return True
  400. except Exception as e:
  401. print(e)
  402. return False
  403. @staticmethod
  404. def rsa_sign(Token):
  405. # 私钥签名Token
  406. if not Token:
  407. return ''
  408. private_key_file = '''-----BEGIN RSA PRIVATE KEY-----
  409. MIIEpQIBAAKCAQEA5iJzEDPqtGmFMggekVro6C0lrjuC2BjunGkrFNJWpDYzxCzE
  410. X5jf4/Fq7hcIaQd5sqHugDxPVollSLPe9zNilbrd0sZfU+Ed8gRVuKW9KwfE9XFr
  411. L0pt6bKRQ0IIRfiZ9TuR0tsQysvcO1GZSXcYfPue3tGM1zOnWFThWDqZ06+sOxzt
  412. RMRl4yNfbpCG4MfxG3itNXOfrjZv2OMLSXrxmzubSvRpUYSvQPs4fm9302SAnySY
  413. 0MKzx6H6528ZQm/IDDSZy6EmNBIyTRDfxC56vnYcXvqedAQh7jJnjdvt6Q4MhASH
  414. eIYi1FBSdu2NT6wgpnrqXzx5pq9kR/lnsLID0wIDAQABAoIBAQCiF4GT1/1oNSpr
  415. ouxk1PNXFPWFUsVGD8mAwVJmx//eiY7MjfuCmdqYYmI+cFqsH2fIOeYSzGfVO9Dq
  416. 9EYHN1oovAWhf7eFDPpajFMUSyiCNmazub8VAAeKowtNpCTPo9pMsDh1m3aoYA4u
  417. ebrN0+Sbo16y8kWRDgDAZoiR7DSMs8lczk16hwfv5mw8XpNDbaL3Coi4Koe2S1Yh
  418. 2SX3vWFlpd7qF1ZYXuZIp+b8JPrV7n9eUKoFgzj0gqgwQK80CoexIjiOrNMPvkQa
  419. q+8kCvFjAzKxOK7e8gjM8lMRiGodb61kmYZkkJzFwWO4EaGbl34lfVECd1Ixp3tF
  420. be0OWAGBAoGBAPSteXDzzToD8ovM7LL11x0jWwI6HOiHu89kZtW566rIezjWBuA2
  421. TxrcYKM3h9jQRXS3CsMdoIv6XGk5lqM8ADtjn23FBWe/THYLh8bm8JOgh5RRWQDg
  422. SvkLfi9Ih2mM4NJfmuuDOh3Nze2efLM7+kOZWUQwF2Zx9mL5jvRBk351AoGBAPDI
  423. sYmT2Li+i5+0vykA2m5uPF8ZOW8BGtAfCZv0suW7BNzSgin78g9WapRd/4p0NNiL
  424. /nVMqPPCpd1akCUpV+GDWQt0hV+HZjxANE0KWhciQRyo2qvo51j8SWILJSgh0tXC
  425. aTF8qt6oGw3VN3m57vKhbrlDaz0J/NDJFci6msAnAoGBAOuG6bXPGijUj+//DYKf
  426. n7jOxdZ49kboEePrtAncdHzri6IEdI3z+WXT6bpzw/LzWUimwldb96WHFNm9s8Hi
  427. Ch8hIODbnP5naUTgiIzw1XhmONyPCewL/F+LrqX5XVA/alNX8JrwsUrrR2WLAGLQ
  428. Q3I69XDsEjptTU2tCO0bCs3ZAoGBAJ2lCHfm0JHET230zONvp5N9oREyVqQSuRdh
  429. +syc3TQDyh85w/bw+X6JOaaCFHj1tFPC9Iqf8k4GNspCLPXnp54CfR4+38O3xnvU
  430. HWoDSRC0YKT++IxtJGriYrlKSr2Hx54kdvLriIPW1D+uRW/xCDza7L9nIKMKEvgv
  431. b4/IfOEpAoGAeKM9Te7T1VzlAkS0CJOwanzwYV/zrex84WuXxlsGgPQ871lTs5AP
  432. H1QLfLfFXH+UVrCEC2yv4eml/cqFkpB3gE5i4MQ8GPVIOSs5tsIyl8YUA03vdNdB
  433. GCqvlyw5dfxNA+EtxNE2wCW/LW7ENJlACgcfgPlBZtpLheWoZB/maw4=
  434. -----END RSA PRIVATE KEY-----'''
  435. # 使用密钥文件方式
  436. # private_key_file_path = os.path.join(BASE_DIR, 'static/iotCore/private.pem')#.replace('\\', '/')
  437. # private_key_file = open(private_key_file_path, 'r')
  438. private_key = ct.load_privatekey(ct.FILETYPE_PEM, private_key_file)
  439. signature = ct.sign(private_key, Token.encode('utf8'), 'sha256')
  440. signature = encodebytes(signature).decode('utf8').replace('\n', '')
  441. # print('signature:', signature)
  442. return signature