CommonService.py 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  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("HTTP_X_FORWARDED_FOR", "")
  60. if not ip:
  61. ip = request.META.get('REMOTE_ADDR', "")
  62. client_ip = ip.split(",")[-1].strip() if ip else ""
  63. return client_ip
  64. # @获取一天每个小时的datetime.datetime
  65. @staticmethod
  66. def getTimeDict(times):
  67. time_dict = {}
  68. t = 0
  69. for x in range(24):
  70. if x < 10:
  71. x = '0' + str(x)
  72. else:
  73. x = str(x)
  74. a = times.strftime("%Y-%m-%d") + " " + x + ":00:00"
  75. time_dict[t] = timezone.datetime.strptime(a, '%Y-%m-%d %H:%M:%S')
  76. t += 1
  77. return time_dict
  78. # 根据ip获取地址
  79. @staticmethod
  80. def getAddr(ip):
  81. base_dir = BASE_DIR
  82. # ip数据库
  83. db = IPIPDatabase(base_dir + '/DB/17monipdb.dat')
  84. addr = db.lookup(ip)
  85. ts = addr.split('\t')[0]
  86. return ts
  87. # 通过ip检索ipip指定信息 lang为CN或EN
  88. @staticmethod
  89. def getIpIpInfo(ip,lang,update=False):
  90. ipbd_dir = BASE_DIR + "/DB/mydata4vipday2.ipdb"
  91. db = ipdb.City(ipbd_dir)
  92. if update:
  93. from var_dump import var_dump
  94. var_dump('is_update')
  95. rr = db.reload(ipbd_dir)
  96. var_dump(rr)
  97. info = db.find_map(ip, lang)
  98. return info
  99. @staticmethod
  100. def getUserID(userPhone='13800138000', getUser=True, setOTAID=False, μs=True):
  101. if μs == True:
  102. if getUser == True:
  103. timeID = str(round(time.time() * 1000000))
  104. userID = timeID + userPhone
  105. return userID
  106. else:
  107. if setOTAID == False:
  108. timeID = str(round(time.time() * 1000000))
  109. ID = userPhone + timeID
  110. return ID
  111. else:
  112. timeID = str(round(time.time() * 1000000))
  113. eID = '13800' + timeID + '138000'
  114. return eID
  115. else:
  116. if getUser == True:
  117. timeID = str(round(time.time() * 1000))
  118. userID = timeID + userPhone
  119. return userID
  120. else:
  121. if setOTAID == False:
  122. timeID = str(round(time.time() * 1000))
  123. ID = userPhone + timeID
  124. return ID
  125. else:
  126. timeID = str(round(time.time() * 1000))
  127. eID = '13800' + timeID + '138000'
  128. return eID
  129. # 生成随机数
  130. @staticmethod
  131. def RandomStr(randomlength=8, number=True):
  132. str = ''
  133. if number == False:
  134. characterSet = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsT' \
  135. 'tUuVvWwXxYyZz0123456789'
  136. else:
  137. characterSet = '0123456789'
  138. length = len(characterSet) - 1
  139. random = Random()
  140. for index in range(randomlength):
  141. str += characterSet[random.randint(0, length)]
  142. return str
  143. # 生成订单好
  144. @staticmethod
  145. def createOrderID():
  146. random_id = CommonService.RandomStr(6, True)
  147. order_id = datetime.datetime.now().strftime('%Y%m%d%H%M%S') + str(random_id)
  148. print('orderID:')
  149. print(order_id)
  150. return order_id
  151. # qs转换list datetime处理
  152. @staticmethod
  153. def qs_to_list(qs):
  154. res = []
  155. # print(qs)
  156. for ps in qs:
  157. if 'add_time' in ps:
  158. ps['add_time'] = ps['add_time'].strftime("%Y-%m-%d %H:%M:%S")
  159. if 'update_time' in ps:
  160. ps['update_time'] = ps['update_time'].strftime("%Y-%m-%d %H:%M:%S")
  161. if 'end_time' in ps:
  162. ps['end_time'] = ps['end_time'].strftime("%Y-%m-%d %H:%M:%S")
  163. if 'data_joined' in ps:
  164. if ps['data_joined']:
  165. ps['data_joined'] = ps['data_joined'].strftime("%Y-%m-%d %H:%M:%S")
  166. else:
  167. ps['data_joined'] = ''
  168. res.append(ps)
  169. return res