CommonService.py 7.0 KB

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