CommonService.py 8.3 KB

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