CommonService.py 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  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.settings import BASE_DIR
  11. from random import Random
  12. # 复用性且公用较高封装代码在这
  13. class CommonService:
  14. # 返回数据格式化
  15. @staticmethod
  16. def response_formal(data={'code': '', 'reason': '', 'result': {}}):
  17. resJSON = json.dumps(
  18. {
  19. "result_code": data['code'],
  20. "reason": data['reason'],
  21. "result": data['result'],
  22. "error_code": data['code'],
  23. }, ensure_ascii=False)
  24. return resJSON
  25. # 添加模糊搜索
  26. @staticmethod
  27. def get_kwargs(data={}):
  28. kwargs = {}
  29. for (k, v) in data.items():
  30. if v is not None and v != u'':
  31. kwargs[k + '__icontains'] = v
  32. return kwargs
  33. # 定义静态方法
  34. # 格式化query_set转dict
  35. @staticmethod
  36. def qs_to_dict(query_set):
  37. sqlJSON = serializers.serialize('json', query_set)
  38. sqlList = json.loads(sqlJSON)
  39. sqlDict = dict(zip(["datas"], [sqlList]))
  40. return sqlDict
  41. @staticmethod
  42. def set_redis_data(key, val, expire=0):
  43. POOL = redis.ConnectionPool(host=SERVER_HOST, port=6379)
  44. CONN = redis.Redis(connection_pool=POOL)
  45. CONN.set(key, val)
  46. if expire > 0:
  47. CONN.expire(key, expire)
  48. return True
  49. @staticmethod
  50. def get_redis_data(key):
  51. POOL = redis.ConnectionPool(host=SERVER_HOST, port=6379)
  52. CONN = redis.Redis(connection_pool=POOL)
  53. try:
  54. val = CONN.get(key)
  55. except Exception as e:
  56. return False
  57. else:
  58. if val == b'False':
  59. return False
  60. if val:
  61. return val
  62. else:
  63. return False
  64. @staticmethod
  65. def del_redis_data(key):
  66. POOL = redis.ConnectionPool(host=SERVER_HOST, port=6379)
  67. CONN = redis.Redis(connection_pool=POOL)
  68. val = CONN.delete(key)
  69. if val:
  70. return True
  71. else:
  72. return False
  73. # 获取文件大小
  74. @staticmethod
  75. def get_file_size(file_path='', suffix_type='', decimal_point=0):
  76. # for x in ['bytes', 'KB', 'MB', 'GB', 'TB']:
  77. # path = Path() / 'D:/TestServer/123444.mp4'
  78. path = Path() / file_path
  79. size = path.stat().st_size
  80. mb_size = 0.0
  81. if suffix_type == 'MB':
  82. mb_size = size / 1024.0 / 1024.0
  83. if decimal_point != 0:
  84. mb_size = round(mb_size, decimal_point)
  85. return mb_size
  86. @staticmethod
  87. def get_param_flag(data=[]):
  88. print(data)
  89. flag = True
  90. for v in data:
  91. if v is None:
  92. flag = False
  93. break
  94. return flag
  95. @staticmethod
  96. def get_ip_address(request):
  97. """
  98. 获取ip地址
  99. :param request:
  100. :return:
  101. """
  102. ip = request.META.get("HTTP_X_FORWARDED_FOR", "")
  103. if not ip:
  104. ip = request.META.get('REMOTE_ADDR', "")
  105. client_ip = ip.split(",")[-1].strip() if ip else ""
  106. return client_ip
  107. # @获取一天每个小时的datetime.datetime
  108. @staticmethod
  109. def getTimeDict(times):
  110. time_dict = {}
  111. t = 0
  112. for x in range(24):
  113. if x < 10:
  114. x = '0' + str(x)
  115. else:
  116. x = str(x)
  117. a = times.strftime("%Y-%m-%d") + " " + x + ":00:00"
  118. time_dict[t] = timezone.datetime.strptime(a, '%Y-%m-%d %H:%M:%S')
  119. t += 1
  120. return time_dict
  121. #根据ip获取地址
  122. @staticmethod
  123. def getAddr(ip):
  124. base_dir = BASE_DIR
  125. # ip数据库
  126. db = IPIPDatabase(base_dir+'/DB/17monipdb.dat')
  127. addr = db.lookup(ip)
  128. ts = addr.split('\t')[0]
  129. return ts
  130. #getMoreID
  131. @staticmethod
  132. def getMoreID(uPhone='13800138000', μs='uID'):
  133. if μs == 'uID':
  134. userID = str(round(time.time() * 1000000)) + uPhone
  135. return userID
  136. elif μs == 'otaID':
  137. otaID = '13800138000' + str(round(time.time() * 1000000))
  138. return otaID
  139. elif μs == 'eID':
  140. eID = '13800' + str(round(time.time() * 1000000)) + '138000'
  141. return eID
  142. elif μs == 'ID':
  143. eID = '13800' + str(round(time.time() * 1000000)) + '138000'
  144. return eID
  145. elif μs == 'gID':
  146. gID = '10000' + str(round(time.time() * 1000000)) + '100001'
  147. return gID
  148. elif μs == 'rID':
  149. rID = '10010' + str(round(time.time() * 1000000)) + '100011'
  150. return rID
  151. else:
  152. defaultID = '10000100001' + str(round(time.time() * 1000000))
  153. return defaultID
  154. # getMoreID
  155. @staticmethod
  156. def getUserID(userPhone='13800138000', getUser=True, setOTAID=False, μs=True):
  157. if μs == True:
  158. if getUser == True:
  159. timeID = str(round(time.time() * 1000000))
  160. userID = timeID + userPhone
  161. return userID
  162. else:
  163. if setOTAID == False:
  164. timeID = str(round(time.time() * 1000000))
  165. ID = userPhone + timeID
  166. return ID
  167. else:
  168. timeID = str(round(time.time() * 1000000))
  169. eID = '13800' + timeID + '138000'
  170. return eID
  171. else:
  172. if getUser == True:
  173. timeID = str(round(time.time() * 1000))
  174. userID = timeID + userPhone
  175. return userID
  176. else:
  177. if setOTAID == False:
  178. timeID = str(round(time.time() * 1000))
  179. ID = userPhone + timeID
  180. return ID
  181. else:
  182. timeID = str(round(time.time() * 1000))
  183. eID = '13800' + timeID + '138000'
  184. return eID
  185. @staticmethod
  186. def get_request_val(key):
  187. request = get_request()
  188. if request.method == 'GET':
  189. request_dict = request.GET
  190. if request.method == 'POST':
  191. request_dict = request.POST
  192. val = request_dict.get(key, None)
  193. return val
  194. @staticmethod
  195. def get_userID_byT(token):
  196. if token == 'stest':
  197. userID = '151547867345163613800138001'
  198. # var_dump(userID)
  199. return userID
  200. if token == 'sformal':
  201. userID = '151564262337939513800138001'
  202. return userID
  203. try:
  204. access_token = token[::-1]
  205. if len(access_token) < 18:
  206. return None
  207. atoken = access_token[:12] + access_token[18:]
  208. try:
  209. token_str = base64.urlsafe_b64decode(atoken).decode('utf-8')
  210. except Exception as e:
  211. print('base64 decode error: %s' % repr(e))
  212. else:
  213. token_list = token_str.split('&')
  214. if len(token_list) != 2:
  215. return None
  216. ts_str = token_list[0]
  217. jsonDict = json.loads(ts_str)
  218. userID = jsonDict.get('userID', None)
  219. except Exception as e:
  220. return None
  221. else:
  222. return userID
  223. @staticmethod
  224. def req_path(request, ssl=False):
  225. get_host = request.get_host() # 获取请求地址
  226. if ssl is True:
  227. tran_p = "https://"
  228. else:
  229. tran_p = "http://"
  230. url_all = tran_p + get_host
  231. return url_all
  232. # 生成随机数
  233. @staticmethod
  234. def RandomStr(randomlength=8, number=True):
  235. str = ''
  236. if number == False:
  237. characterSet = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsT' \
  238. 'tUuVvWwXxYyZz0123456789'
  239. else:
  240. characterSet = '0123456789'
  241. length = len(characterSet) - 1
  242. random = Random()
  243. for index in range(randomlength):
  244. str += characterSet[random.randint(0, length)]
  245. return str