core_views.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. #coding=utf-8
  2. '''
  3. '''
  4. import json
  5. import logging
  6. import re
  7. import traceback
  8. import datetime
  9. import hashlib
  10. from utils.aestool import aescbc
  11. import decimal
  12. import uuid
  13. from django import http
  14. from django.contrib.sessions.backends.cache import SessionStore
  15. from django.core.cache import cache
  16. from django.http import HttpResponse, JsonResponse
  17. from django.shortcuts import render
  18. from django.utils.decorators import method_decorator
  19. from django.views import View
  20. from django.views.decorators.csrf import csrf_exempt
  21. from django.core.serializers.json import DjangoJSONEncoder
  22. from common import error_info
  23. from common.models import UserInfo
  24. import common.models as cm
  25. import common.error_info as ce
  26. logger = logging.getLogger(__name__)
  27. class CusDjangoJSONEncoder(json.JSONEncoder):
  28. """
  29. JSONEncoder subclass that knows how to encode date/time, decimal types and UUIDs.
  30. """
  31. def default(self, o):
  32. # See "Date Time String Format" in the ECMA-262 specification.
  33. if isinstance(o, datetime.datetime):
  34. r = datetime.datetime.strftime(o,'%Y-%m-%d %H:%M:%S')
  35. return r
  36. elif isinstance(o, datetime.date):
  37. return o.isoformat()
  38. elif isinstance(o, datetime.time):
  39. if is_aware(o):
  40. raise ValueError("JSON can't represent timezone-aware times.")
  41. r = o.isoformat()
  42. if o.microsecond:
  43. r = r[:12]
  44. return r
  45. elif isinstance(o, datetime.timedelta):
  46. return duration_iso_string(o)
  47. elif isinstance(o, decimal.Decimal):
  48. return str(o)
  49. elif isinstance(o, uuid.UUID):
  50. return str(o)
  51. else:
  52. return super(DjangoJSONEncoder, self).default(o)
  53. class AuthView(View):
  54. @method_decorator(csrf_exempt)
  55. def dispatch(self, request, *args, **kwargs):
  56. """
  57. @attention: as_view()方法使用该方法来分发不同http method,添加异常处理及登陆校验
  58. """
  59. if request.method.lower() in self.http_method_names:
  60. handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
  61. else:
  62. handler = self.http_method_not_allowed
  63. return api_wapper(handler, request, True, *args, **kwargs)
  64. class AdminView(View):
  65. @method_decorator(csrf_exempt)
  66. def dispatch(self, request, *args, **kwargs):
  67. """
  68. @attention: as_view()方法使用该方法来分发不同http method,添加异常处理及登陆校验
  69. """
  70. self.http_method_names.append("options")
  71. if request.method.lower() in self.http_method_names:
  72. handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
  73. else:
  74. handler = self.http_method_not_allowed
  75. return admin_handler(handler, request, True, *args, **kwargs)
  76. class BaseView(View):
  77. @method_decorator(csrf_exempt)
  78. def dispatch(self, request, *args, **kwargs):
  79. """
  80. @attention: as_view()方法使用该方法来分发不同http method,添加异常处理及登陆校验
  81. """
  82. if request.method.lower() in self.http_method_names:
  83. handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
  84. else:
  85. handler = self.http_method_not_allowed
  86. return api_wapper(handler, request, False, *args, **kwargs)
  87. def api_wapper(handler, request, is_vauth, *args, **kwargs):
  88. """
  89. @attention: 调试API时使用的装饰器
  90. """
  91. req_path = request.META["PATH_INFO"]
  92. ip = request.META.get("HTTP_X_REAL_IP","")
  93. token = request.META.get("HTTP_AUTHORIZATION")
  94. if is_vauth:
  95. if token:
  96. dec_name = aescbc.decrypt(token)
  97. id = dec_name.split("_")[0]
  98. #id = 80
  99. user = cm.UserInfo.objects.filter(id=id).first()
  100. if not user and False:
  101. return JsonResponse({"code":403,"data":{}})
  102. #选手
  103. cur_match_id = cm.Player.objects.filter(user_id=id).order_by("-match_id").first().match_id
  104. player = cm.Player.objects.filter(user_id=id,match_id=cur_match_id).order_by("-id").first()
  105. setattr(request, "ip", get_ip(request))
  106. setattr(request, "user", user)
  107. setattr(request, "player", player)
  108. if request.method == "OPTIONS":
  109. return JsonResponse({})
  110. else:
  111. return JsonResponse({"code":403,"data":{}})
  112. body = request.body if hasattr(request, "body") else ""
  113. if "x-www-form-urlencoded" in request.content_type:
  114. info = http.QueryDict(body).dict()
  115. if not info:
  116. info = request.GET.dict()
  117. elif "application/json" in request.content_type:
  118. info = json.loads(body) if body else {}
  119. if not info:
  120. info = request.GET.dict()
  121. else:
  122. try:
  123. info = json.loads(body) if body else {}
  124. if not info:
  125. info = request.GET.dict()
  126. except Exception as e:
  127. info = {}
  128. setattr(request, "json", info)
  129. try:
  130. ret = handler(request, *args, **kwargs)
  131. return ret
  132. except Exception as e:
  133. return to_fail(e)
  134. def admin_handler(handler, request, is_vauth, *args, **kwargs):
  135. """
  136. 登录session校验
  137. """
  138. req_path = request.META["PATH_INFO"]
  139. ip = request.META.get("HTTP_X_REAL_IP","")
  140. token = request.META.get("HTTP_AUTHORIZATION")
  141. if is_vauth and not request.user.is_authenticated():
  142. return HttpResponse(status=403)
  143. body = request.body if hasattr(request, "body") else ""
  144. if "x-www-form-urlencoded" in request.content_type:
  145. info = http.QueryDict(body).dict()
  146. if not info:
  147. info = request.GET.dict()
  148. elif "application/json" in request.content_type:
  149. info = json.loads(body) if body else {}
  150. if not info:
  151. info = request.GET.dict()
  152. else:
  153. try:
  154. info = json.loads(body) if body else {}
  155. if not info:
  156. info = request.GET.dict()
  157. except:
  158. info = {}
  159. setattr(request, "json", info)
  160. setattr(request, "ip", get_ip(request))
  161. try:
  162. ret = handler(request, *args, **kwargs)
  163. return ret
  164. except Exception as e:
  165. return to_fail(e)
  166. def to_suc(data={}):
  167. info = {}
  168. info["data"] = data
  169. info["code"] = 0
  170. return JsonResponse(info,encoder=CusDjangoJSONEncoder)
  171. def to_fail(e=None):
  172. info = {}
  173. info["code"] = 1000
  174. if isinstance(e,ce.TipException):
  175. info["message"] = e.msg
  176. else:
  177. info["message"] = str(e)
  178. return JsonResponse(info)
  179. def tracefail():
  180. traceback.print_exc()
  181. def stream_file(content, content_type, file_name):
  182. """
  183. 输出文件
  184. :param content: 内容 StringIO 类型
  185. :param content_type: 类型 eg: "application/vnd.ms-excel"
  186. :param file_name: 文件名(需指定后缀)
  187. """
  188. response = HttpResponse(content=content, content_type=content_type)
  189. response['Content-Disposition'] = 'attachment; filename={}'.format(file_name)
  190. return response
  191. def get_ip(request):
  192. if request.META.has_key('HTTP_X_REAL_IP'):
  193. ip = request.META['HTTP_X_REAL_IP']
  194. elif request.META.has_key('HTTP_X_FORWARDED_FOR'):
  195. ip = request.META['HTTP_X_FORWARDED_FOR']
  196. else:
  197. ip = request.META['REMOTE_ADDR']
  198. return ip