CommonService.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492
  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 'add_time' in ps:
  184. ps['add_time'] = ps['add_time'].strftime("%Y-%m-%d %H:%M:%S")
  185. if 'update_time' in ps:
  186. ps['update_time'] = ps['update_time'].strftime("%Y-%m-%d %H:%M:%S")
  187. if 'end_time' in ps:
  188. ps['end_time'] = ps['end_time'].strftime("%Y-%m-%d %H:%M:%S")
  189. if 'data_joined' in ps:
  190. if ps['data_joined']:
  191. ps['data_joined'] = ps['data_joined'].strftime("%Y-%m-%d %H:%M:%S")
  192. else:
  193. ps['data_joined'] = ''
  194. if 'userID__data_joined' in ps:
  195. if ps['userID__data_joined']:
  196. ps['userID__data_joined'] = ps['userID__data_joined'].strftime("%Y-%m-%d %H:%M:%S")
  197. else:
  198. ps['userID__data_joined'] = ''
  199. except Exception as e:
  200. pass
  201. res.append(ps)
  202. return res
  203. # 获取当前时间
  204. @staticmethod
  205. def get_now_time_str(n_time, tz, lang):
  206. print(n_time)
  207. print(tz)
  208. print(lang)
  209. n_time = int(n_time) + 3600 * float(tz)
  210. if lang == 'cn':
  211. return time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(int(n_time)))
  212. else:
  213. return time.strftime('%m-%d-%Y %H:%M:%S', time.gmtime(int(n_time)))
  214. # 生成随机数
  215. @staticmethod
  216. def encrypt_data(randomlength=8, number=False):
  217. str = ''
  218. if number == False:
  219. characterSet = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsT' \
  220. 'tUuVvWwXxYyZz0123456789'
  221. else:
  222. characterSet = '0123456789'
  223. length = len(characterSet) - 1
  224. random = Random()
  225. for index in range(randomlength):
  226. str += characterSet[random.randint(0, length)]
  227. return str
  228. @staticmethod
  229. def decode_data(content, start=1, end=4):
  230. if not content:
  231. return ''
  232. try:
  233. for i in range(start, end):
  234. if i == 1:
  235. content = base64.b64decode(content)
  236. content = content.decode('utf-8')
  237. content = content[1:-1]
  238. if i == 2:
  239. content = base64.b64decode(content)
  240. content = content.decode('utf-8')
  241. content = content[2:-2]
  242. if i == 3:
  243. content = base64.b64decode(content)
  244. content = content.decode('utf-8')
  245. content = content[3:-3]
  246. return content
  247. except Exception as e:
  248. print(e)
  249. return None
  250. @staticmethod
  251. def encode_data(content, start=1, end=4):
  252. if not content:
  253. return ''
  254. for i in range(start, end):
  255. if i == 1:
  256. content = RandomStr(3, False)+content+RandomStr(3, False)
  257. content = base64.b64encode(str(content).encode("utf-8")).decode('utf8')
  258. if i == 2:
  259. content = RandomStr(2, False)+str(content)+RandomStr(2, False)
  260. content = base64.b64encode(str(content).encode("utf-8")).decode('utf8')
  261. if i == 3:
  262. content = RandomStr(1, False)+str(content)+RandomStr(1, False)
  263. content = base64.b64encode(str(content).encode("utf-8")).decode('utf8')
  264. return content
  265. #把格式化时间转换成时间戳
  266. @staticmethod
  267. def str_to_timestamp(str_time=None, format='%Y-%m-%d %H:%M:%S'):
  268. if str_time:
  269. time_tuple = time.strptime(str_time, format) # 把格式化好的时间转换成元祖
  270. result = time.mktime(time_tuple) # 把时间元祖转换成时间戳
  271. return int(result)
  272. return int(time.time())
  273. # 把时间戳转换成格式化
  274. @staticmethod
  275. def timestamp_to_str(timestamp=None, format='%Y-%m-%d %H:%M:%S'):
  276. if timestamp:
  277. time_tuple = time.localtime(timestamp) # 把时间戳转换成时间元祖
  278. result = time.strftime(format, time_tuple) # 把时间元祖转换成格式化好的时间
  279. return result
  280. else:
  281. return time.strptime(format)
  282. #计算N个月后的时间戳
  283. @staticmethod
  284. def calcMonthLater(addMonth, unix_timestamp=None):
  285. if unix_timestamp:
  286. now_year = time.localtime(unix_timestamp).tm_year
  287. now_month = time.localtime(unix_timestamp).tm_mon
  288. now_day = time.localtime(unix_timestamp).tm_mday
  289. now_hour = time.localtime(unix_timestamp).tm_hour
  290. now_min = time.localtime(unix_timestamp).tm_min
  291. now_second = time.localtime(unix_timestamp).tm_sec
  292. else:
  293. now_year = datetime.datetime.now().year
  294. now_month = datetime.datetime.now().month
  295. now_day = datetime.datetime.now().day
  296. now_hour = datetime.datetime.now().hour
  297. now_min = datetime.datetime.now().minute
  298. now_second = datetime.datetime.now().second
  299. for add in range(addMonth):
  300. if now_month == 12:
  301. now_year += 1
  302. now_month = 1
  303. else:
  304. now_month += 1
  305. for is_format in range(4):
  306. try:
  307. date_format = '{now_year}-{now_month}-{now_day} {now_hour}:{now_min}:{now_second}' \
  308. .format(now_year=now_year,now_month=now_month,now_day=now_day,now_hour=now_hour,
  309. now_min=now_min,now_second=now_second)
  310. timestamps = CommonService.str_to_timestamp(date_format)
  311. except Exception as e:
  312. if str(e) == 'day is out of range for month':
  313. now_day = now_day - 1
  314. return timestamps
  315. @staticmethod
  316. def updateMac(mac: str):
  317. macArray = mac.split(':')
  318. macArray[0] = int(macArray[0], 16)
  319. macArray[1] = int(macArray[1], 16)
  320. macArray[2] = int(macArray[2], 16)
  321. first = int(macArray[5], 16)
  322. second = int(macArray[4], 16)
  323. three = int(macArray[3], 16)
  324. # print(macArray)
  325. # print(first)
  326. # print(second)
  327. # print(three)
  328. if first == 255 and second == 255 and three == 255:
  329. return None
  330. first += 1
  331. if first / 256 == 1:
  332. second += 1
  333. first = first % 256
  334. if second / 256 == 1:
  335. three += 1
  336. second = second % 256
  337. macArray[3] = three
  338. macArray[4] = second
  339. macArray[5] = first
  340. # print(macArray)
  341. tmp = ':'.join(map(lambda x: "%02x" % x, macArray))
  342. # print(tmp)
  343. return tmp.upper()
  344. @staticmethod
  345. def decode_data(content, start=1, end=4):
  346. if not content:
  347. return ''
  348. try:
  349. for i in range(start, end):
  350. if i == 1:
  351. content = base64.b64decode(content)
  352. content = content.decode('utf-8')
  353. content = content[1:-1]
  354. if i == 2:
  355. content = base64.b64decode(content)
  356. content = content.decode('utf-8')
  357. content = content[2:-2]
  358. if i == 3:
  359. content = base64.b64decode(content)
  360. content = content.decode('utf-8')
  361. content = content[3:-3]
  362. print(content)
  363. return content
  364. except Exception as e:
  365. print(e)
  366. return None
  367. @staticmethod
  368. def encode_data(content, start=1, end=4):
  369. if not content:
  370. return ''
  371. for i in range(start, end):
  372. if i == 1:
  373. content = CommonService.RandomStr(3, False) + content + CommonService.RandomStr(3, False)
  374. content = base64.b64encode(str(content).encode("utf-8")).decode('utf8')
  375. if i == 2:
  376. content = CommonService.RandomStr(2, False) + str(content) + CommonService.RandomStr(2, False)
  377. content = base64.b64encode(str(content).encode("utf-8")).decode('utf8')
  378. if i == 3:
  379. content = CommonService.RandomStr(1, False) + str(content) + CommonService.RandomStr(1, False)
  380. content = base64.b64encode(str(content).encode("utf-8")).decode('utf8')
  381. return content
  382. @staticmethod
  383. def encode_data_without_salt(content):
  384. return base64.b64encode(str(content).encode("utf-8")).decode('utf8')
  385. @staticmethod
  386. def check_time_stamp_token(token, time_stamp):
  387. # 时间戳token校验
  388. if not all([token, time_stamp]):
  389. return False
  390. try:
  391. token = int(CommonService.decode_data(token))
  392. time_stamp = int(time_stamp)
  393. now_time = int(time.time())
  394. distance = now_time - time_stamp
  395. if token != time_stamp or distance > 60000 or distance < -60000: # 为了全球化时间控制在一天内
  396. return False
  397. return True
  398. except Exception as e:
  399. print(e)
  400. return False
  401. @staticmethod
  402. def rsa_sign(Token):
  403. # 私钥签名Token
  404. if not Token:
  405. return ''
  406. private_key_file = '''-----BEGIN RSA PRIVATE KEY-----
  407. MIIEpQIBAAKCAQEA5iJzEDPqtGmFMggekVro6C0lrjuC2BjunGkrFNJWpDYzxCzE
  408. X5jf4/Fq7hcIaQd5sqHugDxPVollSLPe9zNilbrd0sZfU+Ed8gRVuKW9KwfE9XFr
  409. L0pt6bKRQ0IIRfiZ9TuR0tsQysvcO1GZSXcYfPue3tGM1zOnWFThWDqZ06+sOxzt
  410. RMRl4yNfbpCG4MfxG3itNXOfrjZv2OMLSXrxmzubSvRpUYSvQPs4fm9302SAnySY
  411. 0MKzx6H6528ZQm/IDDSZy6EmNBIyTRDfxC56vnYcXvqedAQh7jJnjdvt6Q4MhASH
  412. eIYi1FBSdu2NT6wgpnrqXzx5pq9kR/lnsLID0wIDAQABAoIBAQCiF4GT1/1oNSpr
  413. ouxk1PNXFPWFUsVGD8mAwVJmx//eiY7MjfuCmdqYYmI+cFqsH2fIOeYSzGfVO9Dq
  414. 9EYHN1oovAWhf7eFDPpajFMUSyiCNmazub8VAAeKowtNpCTPo9pMsDh1m3aoYA4u
  415. ebrN0+Sbo16y8kWRDgDAZoiR7DSMs8lczk16hwfv5mw8XpNDbaL3Coi4Koe2S1Yh
  416. 2SX3vWFlpd7qF1ZYXuZIp+b8JPrV7n9eUKoFgzj0gqgwQK80CoexIjiOrNMPvkQa
  417. q+8kCvFjAzKxOK7e8gjM8lMRiGodb61kmYZkkJzFwWO4EaGbl34lfVECd1Ixp3tF
  418. be0OWAGBAoGBAPSteXDzzToD8ovM7LL11x0jWwI6HOiHu89kZtW566rIezjWBuA2
  419. TxrcYKM3h9jQRXS3CsMdoIv6XGk5lqM8ADtjn23FBWe/THYLh8bm8JOgh5RRWQDg
  420. SvkLfi9Ih2mM4NJfmuuDOh3Nze2efLM7+kOZWUQwF2Zx9mL5jvRBk351AoGBAPDI
  421. sYmT2Li+i5+0vykA2m5uPF8ZOW8BGtAfCZv0suW7BNzSgin78g9WapRd/4p0NNiL
  422. /nVMqPPCpd1akCUpV+GDWQt0hV+HZjxANE0KWhciQRyo2qvo51j8SWILJSgh0tXC
  423. aTF8qt6oGw3VN3m57vKhbrlDaz0J/NDJFci6msAnAoGBAOuG6bXPGijUj+//DYKf
  424. n7jOxdZ49kboEePrtAncdHzri6IEdI3z+WXT6bpzw/LzWUimwldb96WHFNm9s8Hi
  425. Ch8hIODbnP5naUTgiIzw1XhmONyPCewL/F+LrqX5XVA/alNX8JrwsUrrR2WLAGLQ
  426. Q3I69XDsEjptTU2tCO0bCs3ZAoGBAJ2lCHfm0JHET230zONvp5N9oREyVqQSuRdh
  427. +syc3TQDyh85w/bw+X6JOaaCFHj1tFPC9Iqf8k4GNspCLPXnp54CfR4+38O3xnvU
  428. HWoDSRC0YKT++IxtJGriYrlKSr2Hx54kdvLriIPW1D+uRW/xCDza7L9nIKMKEvgv
  429. b4/IfOEpAoGAeKM9Te7T1VzlAkS0CJOwanzwYV/zrex84WuXxlsGgPQ871lTs5AP
  430. H1QLfLfFXH+UVrCEC2yv4eml/cqFkpB3gE5i4MQ8GPVIOSs5tsIyl8YUA03vdNdB
  431. GCqvlyw5dfxNA+EtxNE2wCW/LW7ENJlACgcfgPlBZtpLheWoZB/maw4=
  432. -----END RSA PRIVATE KEY-----'''
  433. # 使用密钥文件方式
  434. # private_key_file_path = os.path.join(BASE_DIR, 'static/iotCore/private.pem')#.replace('\\', '/')
  435. # private_key_file = open(private_key_file_path, 'r')
  436. private_key = ct.load_privatekey(ct.FILETYPE_PEM, private_key_file)
  437. signature = ct.sign(private_key, Token.encode('utf8'), 'sha256')
  438. signature = encodebytes(signature).decode('utf8').replace('\n', '')
  439. # print('signature:', signature)
  440. return signature