CommonService.py 7.3 KB

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