CommonService.py 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  1. # -*- coding: utf-8 -*-
  2. import datetime
  3. import time
  4. from pathlib import Path
  5. from random import Random
  6. import simplejson as json
  7. from django.core import serializers
  8. from django.utils import timezone
  9. from pyipip import IPIPDatabase
  10. from Ansjer.config import BASE_DIR
  11. # 复用性且公用较高封装代码在这
  12. class CommonService:
  13. # 返回数据格式化
  14. @staticmethod
  15. def response_formal(data={'code': '', 'reason': '', 'result': {}}):
  16. resJSON = json.dumps(
  17. {
  18. "result_code": data['code'],
  19. "reason": data['reason'],
  20. "result": data['result'],
  21. "error_code": data['code'],
  22. }, ensure_ascii=False)
  23. return resJSON
  24. # 添加模糊搜索
  25. @staticmethod
  26. def get_kwargs(data={}):
  27. kwargs = {}
  28. for (k, v) in data.items():
  29. if v is not None and v != u'':
  30. kwargs[k + '__icontains'] = v
  31. return kwargs
  32. # 定义静态方法
  33. # 格式化query_set转dict
  34. @staticmethod
  35. def qs_to_dict(query_set):
  36. sqlJSON = serializers.serialize('json', query_set)
  37. sqlList = json.loads(sqlJSON)
  38. sqlDict = dict(zip(["datas"], [sqlList]))
  39. return sqlDict
  40. # 获取文件大小
  41. @staticmethod
  42. def get_file_size(file_path='', suffix_type='', decimal_point=0):
  43. # for x in ['bytes', 'KB', 'MB', 'GB', 'TB']:
  44. # path = Path() / 'D:/TestServer/123444.mp4'
  45. path = Path() / file_path
  46. size = path.stat().st_size
  47. mb_size = 0.0
  48. if suffix_type == 'MB':
  49. mb_size = size / 1024.0 / 1024.0
  50. if decimal_point != 0:
  51. mb_size = round(mb_size, decimal_point)
  52. return mb_size
  53. @staticmethod
  54. def get_param_flag(data=[]):
  55. print(data)
  56. flag = True
  57. for v in data:
  58. if v is None:
  59. flag = False
  60. break
  61. return flag
  62. @staticmethod
  63. def get_ip_address(request):
  64. """
  65. 获取ip地址
  66. :param request:
  67. :return:
  68. """
  69. ip = request.META.get("HTTP_X_FORWARDED_FOR", "")
  70. if not ip:
  71. ip = request.META.get('REMOTE_ADDR', "")
  72. client_ip = ip.split(",")[-1].strip() if ip else ""
  73. return client_ip
  74. # @获取一天每个小时的datetime.datetime
  75. @staticmethod
  76. def getTimeDict(times):
  77. time_dict = {}
  78. t = 0
  79. for x in range(24):
  80. if x < 10:
  81. x = '0' + str(x)
  82. else:
  83. x = str(x)
  84. a = times.strftime("%Y-%m-%d") + " " + x + ":00:00"
  85. time_dict[t] = timezone.datetime.strptime(a, '%Y-%m-%d %H:%M:%S')
  86. t += 1
  87. return time_dict
  88. # 根据ip获取地址
  89. @staticmethod
  90. def getAddr(ip):
  91. base_dir = BASE_DIR
  92. # ip数据库
  93. db = IPIPDatabase(base_dir + '/DB/17monipdb.dat')
  94. addr = db.lookup(ip)
  95. ts = addr.split('\t')[0]
  96. return ts
  97. @staticmethod
  98. def getUserID(userPhone='13800138000', getUser=True, setOTAID=False, μs=True):
  99. if μs == True:
  100. if getUser == True:
  101. timeID = str(round(time.time() * 1000000))
  102. userID = timeID + userPhone
  103. return userID
  104. else:
  105. if setOTAID == False:
  106. timeID = str(round(time.time() * 1000000))
  107. ID = userPhone + timeID
  108. return ID
  109. else:
  110. timeID = str(round(time.time() * 1000000))
  111. eID = '13800' + timeID + '138000'
  112. return eID
  113. else:
  114. if getUser == True:
  115. timeID = str(round(time.time() * 1000))
  116. userID = timeID + userPhone
  117. return userID
  118. else:
  119. if setOTAID == False:
  120. timeID = str(round(time.time() * 1000))
  121. ID = userPhone + timeID
  122. return ID
  123. else:
  124. timeID = str(round(time.time() * 1000))
  125. eID = '13800' + timeID + '138000'
  126. return eID
  127. # 生成随机数
  128. @staticmethod
  129. def RandomStr(randomlength=8, number=True):
  130. str = ''
  131. if number == False:
  132. characterSet = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsT' \
  133. 'tUuVvWwXxYyZz0123456789'
  134. else:
  135. characterSet = '0123456789'
  136. length = len(characterSet) - 1
  137. random = Random()
  138. for index in range(randomlength):
  139. str += characterSet[random.randint(0, length)]
  140. return str
  141. # 生成订单好
  142. @staticmethod
  143. def createOrderID():
  144. random_id = CommonService.RandomStr(6,True)
  145. order_id = datetime.datetime.now().strftime('%Y%m%d%H%M%S') + str(random_id)
  146. print('orderID:')
  147. print(order_id)
  148. return order_id
  149. # qs转换list datetime处理
  150. @staticmethod
  151. def qs_to_list(qs):
  152. res = []
  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. res.append(ps)
  161. return res
  162. # 获取utc时间戳
  163. @staticmethod
  164. def get_utc():
  165. nowdtm = datetime.datetime.utcnow()
  166. un_time = time.mktime(nowdtm.timetuple())
  167. return int(un_time)