CommonService.py 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  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 Ansjer.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. ip = request.META.get("X_FORWARDED_FOR","")
  60. if ip:
  61. client_ip = ip.split(",")[0].strip() if ip else ""
  62. if client_ip:
  63. return client_ip
  64. ip = request.META.get("HTTP_X_FORWARDED_FOR", "")
  65. if not ip:
  66. ip = request.META.get('REMOTE_ADDR', "")
  67. client_ip = ip.split(",")[-1].strip() if ip else ""
  68. return client_ip
  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