CommonService.py 8.0 KB

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