CommonService.py 5.5 KB

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