CommonService.py 7.4 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.settings import SERVER_HOST
  9. from django_global_request.middleware import get_request
  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 query_set_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. @staticmethod
  185. def get_request_val(key):
  186. request = get_request()
  187. if request.method == 'GET':
  188. request_dict = request.GET
  189. if request.method == 'POST':
  190. request_dict = request.POST
  191. val = request_dict.get(key, None)
  192. return val
  193. @staticmethod
  194. def get_userID_byT(token):
  195. if token == 'stest':
  196. userID = '151547867345163613800138001'
  197. # var_dump(userID)
  198. return userID
  199. if token == 'sformal':
  200. userID = '151564262337939513800138001'
  201. return userID
  202. try:
  203. access_token = token[::-1]
  204. if len(access_token) < 18:
  205. return None
  206. atoken = access_token[:12] + access_token[18:]
  207. try:
  208. token_str = base64.urlsafe_b64decode(atoken).decode('utf-8')
  209. except Exception as e:
  210. print('base64 decode error: %s' % repr(e))
  211. else:
  212. token_list = token_str.split('&')
  213. if len(token_list) != 2:
  214. return None
  215. ts_str = token_list[0]
  216. jsonDict = json.loads(ts_str)
  217. userID = jsonDict.get('userID', None)
  218. except Exception as e:
  219. return None
  220. else:
  221. return userID