CommonService.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. # -*- coding: utf-8 -*-
  2. from pathlib import Path
  3. from random import Random
  4. import redis
  5. import simplejson as json
  6. import time
  7. from django.core import serializers
  8. from django.utils import timezone
  9. from pyipip import IPIPDatabase
  10. from Ansjer.config import BASE_DIR, SERVER_HOST
  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. @staticmethod
  41. def set_redis_data(key, val, expire=0):
  42. POOL = redis.ConnectionPool(host=SERVER_HOST, port=6379)
  43. CONN = redis.Redis(connection_pool=POOL)
  44. CONN.set(key, val)
  45. if expire > 0:
  46. CONN.expire(key, expire)
  47. return True
  48. @staticmethod
  49. def get_redis_data(key):
  50. POOL = redis.ConnectionPool(host=SERVER_HOST, port=6379)
  51. CONN = redis.Redis(connection_pool=POOL)
  52. try:
  53. val = CONN.get(key)
  54. except Exception as e:
  55. return False
  56. else:
  57. if val == b'False':
  58. return False
  59. if val:
  60. return val
  61. else:
  62. return False
  63. @staticmethod
  64. def del_redis_data(key):
  65. POOL = redis.ConnectionPool(host=SERVER_HOST, port=6379)
  66. CONN = redis.Redis(connection_pool=POOL)
  67. val = CONN.delete(key)
  68. if val:
  69. return True
  70. else:
  71. return False
  72. # 获取文件大小
  73. @staticmethod
  74. def get_file_size(file_path='', suffix_type='', decimal_point=0):
  75. # for x in ['bytes', 'KB', 'MB', 'GB', 'TB']:
  76. # path = Path() / 'D:/TestServer/123444.mp4'
  77. path = Path() / file_path
  78. size = path.stat().st_size
  79. mb_size = 0.0
  80. if suffix_type == 'MB':
  81. mb_size = size / 1024.0 / 1024.0
  82. if decimal_point != 0:
  83. mb_size = round(mb_size, decimal_point)
  84. return mb_size
  85. @staticmethod
  86. def get_param_flag(data=[]):
  87. print(data)
  88. flag = True
  89. for v in data:
  90. if v is None:
  91. flag = False
  92. break
  93. return flag
  94. @staticmethod
  95. def get_ip_address(request):
  96. """
  97. 获取ip地址
  98. :param request:
  99. :return:
  100. """
  101. ip = request.META.get("HTTP_X_FORWARDED_FOR", "")
  102. if not ip:
  103. ip = request.META.get('REMOTE_ADDR', "")
  104. client_ip = ip.split(",")[-1].strip() if ip else ""
  105. return client_ip
  106. # @获取一天每个小时的datetime.datetime
  107. @staticmethod
  108. def getTimeDict(times):
  109. time_dict = {}
  110. t = 0
  111. for x in range(24):
  112. if x < 10:
  113. x = '0' + str(x)
  114. else:
  115. x = str(x)
  116. a = times.strftime("%Y-%m-%d") + " " + x + ":00:00"
  117. time_dict[t] = timezone.datetime.strptime(a, '%Y-%m-%d %H:%M:%S')
  118. t += 1
  119. return time_dict
  120. #根据ip获取地址
  121. @staticmethod
  122. def getAddr(ip):
  123. base_dir = BASE_DIR
  124. # ip数据库
  125. db = IPIPDatabase(base_dir+'/DB/17monipdb.dat')
  126. addr = db.lookup(ip)
  127. ts = addr.split('\t')[0]
  128. return ts
  129. #getMoreID
  130. @staticmethod
  131. def getMoreID(uPhone='13800138000', μs='uID'):
  132. if μs == 'uID':
  133. userID = str(round(time.time() * 1000000)) + uPhone
  134. return userID
  135. elif μs == 'otaID':
  136. otaID = '13800138000' + str(round(time.time() * 1000000))
  137. return otaID
  138. elif μs == 'eID':
  139. eID = '13800' + str(round(time.time() * 1000000)) + '138000'
  140. return eID
  141. elif μs == 'ID':
  142. eID = '13800' + str(round(time.time() * 1000000)) + '138000'
  143. return eID
  144. elif μs == 'gID':
  145. gID = '10000' + str(round(time.time() * 1000000)) + '100001'
  146. return gID
  147. elif μs == 'rID':
  148. rID = '10010' + str(round(time.time() * 1000000)) + '100011'
  149. return rID
  150. else:
  151. defaultID = '10000100001' + str(round(time.time() * 1000000))
  152. return defaultID
  153. # getMoreID
  154. @staticmethod
  155. def getUserID(userPhone='13800138000', getUser=True, setOTAID=False, μs=True):
  156. if μs == True:
  157. if getUser == True:
  158. timeID = str(round(time.time() * 1000000))
  159. userID = timeID + userPhone
  160. return userID
  161. else:
  162. if setOTAID == False:
  163. timeID = str(round(time.time() * 1000000))
  164. ID = userPhone + timeID
  165. return ID
  166. else:
  167. timeID = str(round(time.time() * 1000000))
  168. eID = '13800' + timeID + '138000'
  169. return eID
  170. else:
  171. if getUser == True:
  172. timeID = str(round(time.time() * 1000))
  173. userID = timeID + userPhone
  174. return userID
  175. else:
  176. if setOTAID == False:
  177. timeID = str(round(time.time() * 1000))
  178. ID = userPhone + timeID
  179. return ID
  180. else:
  181. timeID = str(round(time.time() * 1000))
  182. eID = '13800' + timeID + '138000'
  183. return eID
  184. # 生成随机数
  185. @staticmethod
  186. def RandomStr(randomlength=8, number=True):
  187. str = ''
  188. if number == False:
  189. characterSet = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsT' \
  190. 'tUuVvWwXxYyZz0123456789'
  191. else:
  192. characterSet = '0123456789'
  193. length = len(characterSet) - 1
  194. random = Random()
  195. for index in range(randomlength):
  196. str += characterSet[random.randint(0, length)]
  197. return str