CommonService.py 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  1. # -*- coding: utf-8 -*-
  2. import base64
  3. import datetime
  4. import os
  5. import time
  6. import hashlib
  7. from pathlib import Path
  8. from random import Random
  9. import ipdb
  10. import simplejson as json
  11. from boto3 import Session
  12. from django.core import serializers
  13. from django.utils import timezone
  14. from pyipip import IPIPDatabase
  15. from AnsjerPush.config import BASE_DIR, ACCESS_KEY_ID, SECRET_ACCESS_KEY, REGION_NAME, PUSH_BUCKET
  16. # 复用性且公用较高封装代码在这
  17. class CommonService:
  18. # 添加模糊搜索
  19. @staticmethod
  20. def get_kwargs(data={}):
  21. kwargs = {}
  22. for (k, v) in data.items():
  23. if v is not None and v != u'':
  24. kwargs[k + '__icontains'] = v
  25. return kwargs
  26. # 定义静态方法
  27. # 格式化query_set转dict
  28. @staticmethod
  29. def qs_to_dict(query_set):
  30. sqlJSON = serializers.serialize('json', query_set)
  31. sqlList = json.loads(sqlJSON)
  32. sqlDict = dict(zip(["datas"], [sqlList]))
  33. return sqlDict
  34. # 获取文件大小
  35. @staticmethod
  36. def get_file_size(file_path='', suffix_type='', decimal_point=0):
  37. # for x in ['bytes', 'KB', 'MB', 'GB', 'TB']:
  38. # path = Path() / 'D:/TestServer/123444.mp4'
  39. path = Path() / file_path
  40. size = path.stat().st_size
  41. mb_size = 0.0
  42. if suffix_type == 'MB':
  43. mb_size = size / 1024.0 / 1024.0
  44. if decimal_point != 0:
  45. mb_size = round(mb_size, decimal_point)
  46. return mb_size
  47. @staticmethod
  48. def get_param_flag(data=[]):
  49. # print(data)
  50. flag = True
  51. for v in data:
  52. if v is None:
  53. flag = False
  54. break
  55. return flag
  56. @staticmethod
  57. def get_ip_address(request):
  58. """
  59. 获取ip地址
  60. :param request:
  61. :return:
  62. """
  63. try:
  64. real_ip = request.META['HTTP_X_FORWARDED_FOR']
  65. clientIP = real_ip.split(",")[0]
  66. except:
  67. try:
  68. clientIP = request.META['REMOTE_ADDR']
  69. except Exception as e:
  70. clientIP = ''
  71. return clientIP
  72. # @获取一天每个小时的datetime.datetime
  73. @staticmethod
  74. def getTimeDict(times):
  75. time_dict = {}
  76. t = 0
  77. for x in range(24):
  78. if x < 10:
  79. x = '0' + str(x)
  80. else:
  81. x = str(x)
  82. a = times.strftime("%Y-%m-%d") + " " + x + ":00:00"
  83. time_dict[t] = timezone.datetime.strptime(a, '%Y-%m-%d %H:%M:%S')
  84. t += 1
  85. return time_dict
  86. # 根据ip获取地址
  87. @staticmethod
  88. def getAddr(ip):
  89. base_dir = BASE_DIR
  90. # ip数据库
  91. db = IPIPDatabase(base_dir + '/DB/17monipdb.dat')
  92. addr = db.lookup(ip)
  93. ts = addr.split('\t')[0]
  94. return ts
  95. # 通过ip检索ipip指定信息 lang为CN或EN
  96. @staticmethod
  97. def getIpIpInfo(ip, lang, update=False):
  98. ipbd_dir = BASE_DIR + "/DB/mydata4vipday2.ipdb"
  99. db = ipdb.City(ipbd_dir)
  100. if update:
  101. from var_dump import var_dump
  102. var_dump('is_update')
  103. rr = db.reload(ipbd_dir)
  104. var_dump(rr)
  105. info = db.find_map(ip, lang)
  106. return info
  107. @staticmethod
  108. def getUserID(userPhone='13800138000', getUser=True, setOTAID=False, μs=True):
  109. if μs == True:
  110. if getUser == True:
  111. timeID = str(round(time.time() * 1000000))
  112. userID = timeID + userPhone
  113. return userID
  114. else:
  115. if setOTAID == False:
  116. timeID = str(round(time.time() * 1000000))
  117. ID = userPhone + timeID
  118. return ID
  119. else:
  120. timeID = str(round(time.time() * 1000000))
  121. eID = '13800' + timeID + '138000'
  122. return eID
  123. else:
  124. if getUser == True:
  125. timeID = str(round(time.time() * 1000))
  126. userID = timeID + userPhone
  127. return userID
  128. else:
  129. if setOTAID == False:
  130. timeID = str(round(time.time() * 1000))
  131. ID = userPhone + timeID
  132. return ID
  133. else:
  134. timeID = str(round(time.time() * 1000))
  135. eID = '13800' + timeID + '138000'
  136. return eID
  137. # 生成随机数
  138. @staticmethod
  139. def RandomStr(randomlength=8, number=True):
  140. str = ''
  141. if number == False:
  142. characterSet = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsT' \
  143. 'tUuVvWwXxYyZz0123456789'
  144. else:
  145. characterSet = '0123456789'
  146. length = len(characterSet) - 1
  147. random = Random()
  148. for index in range(randomlength):
  149. str += characterSet[random.randint(0, length)]
  150. return str
  151. # 生成订单好
  152. @staticmethod
  153. def createOrderID():
  154. random_id = CommonService.RandomStr(6, True)
  155. order_id = datetime.datetime.now().strftime('%Y%m%d%H%M%S') + str(random_id)
  156. print('orderID:')
  157. print(order_id)
  158. return order_id
  159. # qs转换list datetime处理
  160. @staticmethod
  161. def qs_to_list(qs):
  162. res = []
  163. # print(qs)
  164. for ps in qs:
  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. res.append(ps)
  177. return res
  178. # 获取当前时间
  179. @staticmethod
  180. def get_now_time_str(n_time, tz, lang):
  181. print(n_time)
  182. print(tz)
  183. print(lang)
  184. try:
  185. tz = tz.replace(':', '.')
  186. n_time = int(n_time) + 3600 * float(tz)
  187. except:
  188. n_time = int(n_time)
  189. if lang == 'cn':
  190. return time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(int(n_time)))
  191. else:
  192. return time.strftime('%m-%d-%Y %H:%M:%S', time.gmtime(int(n_time)))
  193. @staticmethod
  194. def app_log_log(uid='None', tz='0'):
  195. file_path = '/'.join((BASE_DIR, 'static/app_log.log'))
  196. file = open(file_path, 'a+')
  197. file.write("uid:" + uid + "; " + "; tz:" + tz)
  198. file.write('\n')
  199. file.flush()
  200. file.close()
  201. @classmethod
  202. def upload_images(cls, file_dict, dir_path):
  203. """
  204. 上传图片到S3,并删除本地图片
  205. @param file_dict: S3图片路径
  206. @param dir_path: 本地图片路径
  207. @return: boolean
  208. """
  209. try:
  210. s3 = Session(
  211. aws_access_key_id=ACCESS_KEY_ID,
  212. aws_secret_access_key=SECRET_ACCESS_KEY,
  213. region_name=REGION_NAME
  214. ).resource('s3')
  215. for file_path, upload_path in file_dict.items():
  216. upload_data = open(file_path, 'rb')
  217. s3.Bucket(PUSH_BUCKET).put_object(Key=upload_path, Body=upload_data)
  218. # 删除图片
  219. cls.del_path(dir_path)
  220. cls.del_path(dir_path + '.jpg')
  221. return True
  222. except Exception as e:
  223. print(repr(e))
  224. return False
  225. @classmethod
  226. def del_path(cls, path):
  227. """
  228. 删除目录文件
  229. @param path: 文件路径
  230. @return: None
  231. """
  232. if not os.path.exists(path):
  233. return
  234. if os.path.isfile(path):
  235. os.remove(path)
  236. else:
  237. items = os.listdir(path)
  238. for f in items:
  239. c_path = os.path.join(path, f)
  240. if os.path.isdir(c_path):
  241. cls.del_path(c_path)
  242. else:
  243. os.remove(c_path)
  244. os.rmdir(path)
  245. @staticmethod
  246. def getMD5Sign(data, key):
  247. '''
  248. 魅族MD5签名
  249. '''
  250. dataList = []
  251. for k in sorted(data):
  252. dataList.append("%s=%s" % (k, data[k]))
  253. data = (''.join(dataList))
  254. data = data + key
  255. sign = hashlib.md5(data.encode(encoding="utf-8")).hexdigest()
  256. return sign
  257. @staticmethod
  258. def check_time_stamp_token(token, time_stamp):
  259. # 时间戳token校验
  260. if not all([token, time_stamp]):
  261. return False
  262. try:
  263. token = int(CommonService.decode_data(token))
  264. time_stamp = int(time_stamp)
  265. now_time = int(time.time())
  266. distance = now_time - time_stamp
  267. if token != time_stamp or distance > 60000 or distance < -60000: # 为了全球化时间控制在一天内
  268. return False
  269. return True
  270. except Exception as e:
  271. print(e)
  272. return False
  273. @staticmethod
  274. def decode_data(content, start=1, end=4):
  275. """
  276. 数据解密
  277. @param content: 数据内容
  278. @param start: 起始长度
  279. @param end: 结束长度
  280. @return content: 解密的数据
  281. """
  282. if not content:
  283. return ''
  284. for i in range(start, end):
  285. content = base64.b64decode(content)
  286. content = content.decode('utf-8')
  287. content = content[i:-i]
  288. return content