CommonService.py 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  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):
  90. db = ipdb.City(BASE_DIR + "/DB/mydata4vipday2.ipdb")
  91. info = db.find_map(ip, lang)
  92. return info
  93. @staticmethod
  94. def getUserID(userPhone='13800138000', getUser=True, setOTAID=False, μs=True):
  95. if μs == True:
  96. if getUser == True:
  97. timeID = str(round(time.time() * 1000000))
  98. userID = timeID + userPhone
  99. return userID
  100. else:
  101. if setOTAID == False:
  102. timeID = str(round(time.time() * 1000000))
  103. ID = userPhone + timeID
  104. return ID
  105. else:
  106. timeID = str(round(time.time() * 1000000))
  107. eID = '13800' + timeID + '138000'
  108. return eID
  109. else:
  110. if getUser == True:
  111. timeID = str(round(time.time() * 1000))
  112. userID = timeID + userPhone
  113. return userID
  114. else:
  115. if setOTAID == False:
  116. timeID = str(round(time.time() * 1000))
  117. ID = userPhone + timeID
  118. return ID
  119. else:
  120. timeID = str(round(time.time() * 1000))
  121. eID = '13800' + timeID + '138000'
  122. return eID
  123. # 生成随机数
  124. @staticmethod
  125. def RandomStr(randomlength=8, number=True):
  126. str = ''
  127. if number == False:
  128. characterSet = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsT' \
  129. 'tUuVvWwXxYyZz0123456789'
  130. else:
  131. characterSet = '0123456789'
  132. length = len(characterSet) - 1
  133. random = Random()
  134. for index in range(randomlength):
  135. str += characterSet[random.randint(0, length)]
  136. return str
  137. # 生成订单好
  138. @staticmethod
  139. def createOrderID():
  140. random_id = CommonService.RandomStr(6, True)
  141. order_id = datetime.datetime.now().strftime('%Y%m%d%H%M%S') + str(random_id)
  142. print('orderID:')
  143. print(order_id)
  144. return order_id
  145. # qs转换list datetime处理
  146. @staticmethod
  147. def qs_to_list(qs):
  148. res = []
  149. # print(qs)
  150. for ps in qs:
  151. if 'add_time' in ps:
  152. ps['add_time'] = ps['add_time'].strftime("%Y-%m-%d %H:%M:%S")
  153. if 'update_time' in ps:
  154. ps['update_time'] = ps['update_time'].strftime("%Y-%m-%d %H:%M:%S")
  155. if 'end_time' in ps:
  156. ps['end_time'] = ps['end_time'].strftime("%Y-%m-%d %H:%M:%S")
  157. if 'data_joined' in ps:
  158. if ps['data_joined']:
  159. ps['data_joined'] = ps['data_joined'].strftime("%Y-%m-%d %H:%M:%S")
  160. else:
  161. ps['data_joined'] = ''
  162. res.append(ps)
  163. return res