CommonService.py 6.5 KB

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