CommonService.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  1. # -*- coding: utf-8 -*-
  2. import time,datetime
  3. from pathlib import Path
  4. from random import Random
  5. import simplejson as json
  6. from django.core import serializers
  7. from django.utils import timezone
  8. from pyipip import IPIPDatabase
  9. from Ansjer.config import BASE_DIR
  10. # 复用性且公用较高封装代码在这
  11. class CommonService:
  12. # 返回数据格式化
  13. @staticmethod
  14. def response_formal(data={'code': '', 'reason': '', 'result': {}}):
  15. resJSON = json.dumps(
  16. {
  17. "result_code": data['code'],
  18. "reason": data['reason'],
  19. "result": data['result'],
  20. "error_code": data['code'],
  21. }, ensure_ascii=False)
  22. return resJSON
  23. # 添加模糊搜索
  24. @staticmethod
  25. def get_kwargs(data={}):
  26. kwargs = {}
  27. for (k, v) in data.items():
  28. if v is not None and v != u'':
  29. kwargs[k + '__icontains'] = v
  30. return kwargs
  31. # 定义静态方法
  32. # 格式化query_set转dict
  33. @staticmethod
  34. def qs_to_dict(query_set):
  35. sqlJSON = serializers.serialize('json', query_set)
  36. sqlList = json.loads(sqlJSON)
  37. sqlDict = dict(zip(["datas"], [sqlList]))
  38. return sqlDict
  39. # 获取文件大小
  40. @staticmethod
  41. def get_file_size(file_path='', suffix_type='', decimal_point=0):
  42. # for x in ['bytes', 'KB', 'MB', 'GB', 'TB']:
  43. # path = Path() / 'D:/TestServer/123444.mp4'
  44. path = Path() / file_path
  45. size = path.stat().st_size
  46. mb_size = 0.0
  47. if suffix_type == 'MB':
  48. mb_size = size / 1024.0 / 1024.0
  49. if decimal_point != 0:
  50. mb_size = round(mb_size, decimal_point)
  51. return mb_size
  52. @staticmethod
  53. def get_param_flag(data=[]):
  54. print(data)
  55. flag = True
  56. for v in data:
  57. if v is None:
  58. flag = False
  59. break
  60. return flag
  61. @staticmethod
  62. def get_ip_address(request):
  63. """
  64. 获取ip地址
  65. :param request:
  66. :return:
  67. """
  68. ip = request.META.get("HTTP_X_FORWARDED_FOR", "")
  69. if not ip:
  70. ip = request.META.get('REMOTE_ADDR', "")
  71. client_ip = ip.split(",")[-1].strip() if ip else ""
  72. return client_ip
  73. # @获取一天每个小时的datetime.datetime
  74. @staticmethod
  75. def getTimeDict(times):
  76. time_dict = {}
  77. t = 0
  78. for x in range(24):
  79. if x < 10:
  80. x = '0' + str(x)
  81. else:
  82. x = str(x)
  83. a = times.strftime("%Y-%m-%d") + " " + x + ":00:00"
  84. time_dict[t] = timezone.datetime.strptime(a, '%Y-%m-%d %H:%M:%S')
  85. t += 1
  86. return time_dict
  87. # 根据ip获取地址
  88. @staticmethod
  89. def getAddr(ip):
  90. base_dir = BASE_DIR
  91. # ip数据库
  92. db = IPIPDatabase(base_dir + '/DB/17monipdb.dat')
  93. addr = db.lookup(ip)
  94. ts = addr.split('\t')[0]
  95. return ts
  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 createID():
  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. for ps in qs:
  153. if 'add_time' in ps:
  154. ps['add_time'] = ps['add_time'].strftime("%Y-%m-%d %H:%M:%S")
  155. if 'update_time' in ps:
  156. ps['update_time'] = ps['update_time'].strftime("%Y-%m-%d %H:%M:%S")
  157. if 'end_time' in ps:
  158. ps['end_time'] = ps['end_time'].strftime("%Y-%m-%d %H:%M:%S")
  159. res.append(ps)
  160. return res