core_views.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  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. from django import http
  12. from django.contrib.sessions.backends.cache import SessionStore
  13. from django.core.cache import cache
  14. from django.http import HttpResponse, JsonResponse
  15. from django.shortcuts import render
  16. from django.utils.decorators import method_decorator
  17. from django.views import View
  18. from django.views.decorators.csrf import csrf_exempt
  19. from django.core.serializers.json import DjangoJSONEncoder
  20. from common import error_info
  21. from common.models import UserInfo
  22. import common.models as cm
  23. import common.error_info as ce
  24. logger = logging.getLogger(__name__)
  25. class CusDjangoJSONEncoder(json.JSONEncoder):
  26. """
  27. JSONEncoder subclass that knows how to encode date/time, decimal types and UUIDs.
  28. """
  29. def default(self, o):
  30. # See "Date Time String Format" in the ECMA-262 specification.
  31. if isinstance(o, datetime.datetime):
  32. r = datetime.datetime.strftime(o,'%Y-%m-%d %H:%M:%S')
  33. return r
  34. elif isinstance(o, datetime.date):
  35. return o.isoformat()
  36. elif isinstance(o, datetime.time):
  37. if is_aware(o):
  38. raise ValueError("JSON can't represent timezone-aware times.")
  39. r = o.isoformat()
  40. if o.microsecond:
  41. r = r[:12]
  42. return r
  43. elif isinstance(o, datetime.timedelta):
  44. return duration_iso_string(o)
  45. elif isinstance(o, decimal.Decimal):
  46. return str(o)
  47. elif isinstance(o, uuid.UUID):
  48. return str(o)
  49. elif isinstance(o, Promise):
  50. return six.text_type(o)
  51. elif isinstance(o, CallableBool):
  52. return bool(o)
  53. else:
  54. return super(DjangoJSONEncoder, self).default(o)
  55. class AuthView(View):
  56. @method_decorator(csrf_exempt)
  57. def dispatch(self, request, *args, **kwargs):
  58. """
  59. @attention: as_view()方法使用该方法来分发不同http method,添加异常处理及登陆校验
  60. """
  61. if request.method.lower() in self.http_method_names:
  62. handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
  63. else:
  64. handler = self.http_method_not_allowed
  65. return api_wapper(handler, request, True, *args, **kwargs)
  66. class AdminView(View):
  67. @method_decorator(csrf_exempt)
  68. def dispatch(self, request, *args, **kwargs):
  69. """
  70. @attention: as_view()方法使用该方法来分发不同http method,添加异常处理及登陆校验
  71. """
  72. self.http_method_names.append("options")
  73. if request.method.lower() in self.http_method_names:
  74. handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
  75. else:
  76. handler = self.http_method_not_allowed
  77. return admin_handler(handler, request, True, *args, **kwargs)
  78. class YRXView(View):
  79. @method_decorator(csrf_exempt)
  80. def dispatch(self, request, *args, **kwargs):
  81. """
  82. @attention: as_view()方法使用该方法来分发不同http method,添加异常处理及登陆校验
  83. """
  84. self.http_method_names.append("options")
  85. if request.method.lower() in self.http_method_names:
  86. handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
  87. else:
  88. handler = self.http_method_not_allowed
  89. return yrx_handler(handler, request, True, *args, **kwargs)
  90. class BaseView(View):
  91. @method_decorator(csrf_exempt)
  92. def dispatch(self, request, *args, **kwargs):
  93. """
  94. @attention: as_view()方法使用该方法来分发不同http method,添加异常处理及登陆校验
  95. """
  96. if request.method.lower() in self.http_method_names:
  97. handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
  98. else:
  99. handler = self.http_method_not_allowed
  100. return api_wapper(handler, request, False, *args, **kwargs)
  101. class UploadView(View):
  102. @method_decorator(csrf_exempt)
  103. def dispatch(self, request, *args, **kwargs):
  104. """
  105. @attention: as_view()方法使用该方法来分发不同http method,添加异常处理及登陆校验
  106. """
  107. if request.method.lower() in self.http_method_names:
  108. handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
  109. else:
  110. handler = self.http_method_not_allowed
  111. return upload_wapper(handler,request,True, *args, **kwargs)
  112. class InnerView(View):
  113. @method_decorator(csrf_exempt)
  114. def dispatch(self, request, *args, **kwargs):
  115. """
  116. @attention: as_view()方法使用该方法来分发不同http method,添加异常处理及登陆校验
  117. """
  118. if request.method.lower() in self.http_method_names:
  119. handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
  120. if request.META.get("HTTP_TOKEN") != "7dpHIhpweckghdoSvrXwMftcjZRIzKwJ":
  121. handler = self.http_method_not_allowed
  122. else:
  123. handler = self.http_method_not_allowed
  124. return api_wapper(handler, request, False, *args, **kwargs)
  125. def show_history(request):
  126. logined_history = cache.get("logined_history", {})
  127. for k, v in logined_history.iteritems():
  128. logger.info("k: %s, v: %s", str(k), str(v))
  129. logger.info("current session: %s", str(request.session.session_key))
  130. ss = SessionStore(request.session.session_key)
  131. for k, v in ss.iteritems():
  132. logger.info("k: %s, v: %s", str(k), str(v))
  133. def api_wapper(handler, request, is_vauth, *args, **kwargs):
  134. """
  135. @attention: 调试API时使用的装饰器
  136. """
  137. req_path = request.META["PATH_INFO"]
  138. ip = request.META.get("HTTP_X_REAL_IP","")
  139. token = request.META.get("HTTP_AUTHORIZATION")
  140. if is_vauth:
  141. if token:
  142. dec_name = aescbc.decrypt(token)
  143. name = dec_name.split("_")[0]
  144. utype = dec_name.split("_")[1]
  145. if utype == 1:
  146. user = cm.Goverment.objects.filter(id=name).first()
  147. elif utype == 2:
  148. user = cm.EnterPrise.objects.filter(id=name).first()
  149. else:
  150. user = cm.StaffUser.objects.filter(id=name).first()
  151. if not user and False:
  152. return JsonResponse({"code":403,"data":{}})
  153. #return HttpResponse(status=403)
  154. setattr(request, "ip", get_ip(request))
  155. setattr(request, "user", user)
  156. setattr(request, "utype", utype)
  157. if request.method == "OPTIONS":
  158. return JsonResponse({})
  159. else:
  160. return JsonResponse({"code":403,"data":{}})
  161. body = request.body if hasattr(request, "body") else ""
  162. if "x-www-form-urlencoded" in request.content_type:
  163. info = http.QueryDict(body).dict()
  164. if not info:
  165. info = request.GET.dict()
  166. elif "application/json" in request.content_type:
  167. info = json.loads(body) if body else {}
  168. if not info:
  169. info = request.GET.dict()
  170. else:
  171. try:
  172. info = json.loads(body) if body else {}
  173. if not info:
  174. info = request.GET.dict()
  175. except:
  176. info = {}
  177. setattr(request, "json", info)
  178. try:
  179. ret = handler(request, *args, **kwargs)
  180. return ret
  181. except Exception as e:
  182. return to_fail(e)
  183. def admin_handler(handler, request, is_vauth, *args, **kwargs):
  184. """
  185. 登录session校验
  186. """
  187. req_path = request.META["PATH_INFO"]
  188. ip = request.META.get("HTTP_X_REAL_IP","")
  189. token = request.META.get("HTTP_AUTHORIZATION")
  190. if is_vauth and token:
  191. dectoken = aescbc.decrypt(token)
  192. name = dectoken.split("_")[0]
  193. utype = dectoken.split("_")[1]
  194. if str(utype) == "0":
  195. user = UserInfo.objects.filter(id=name).first()
  196. elif str(utype) == "1":
  197. user = cm.Goverment.objects.filter(id=name).first()
  198. else:
  199. user = cm.EnterPrise.objects.filter(id=name).first()
  200. if not user and False:
  201. #return JsonResponse({"code":403,"data":{}})
  202. return HttpResponse(status=403)
  203. setattr(request, "ip", get_ip(request))
  204. setattr(request, "user", user)
  205. setattr(request, "utype", utype)
  206. if request.method == "OPTIONS":
  207. return JsonResponse({})
  208. body = request.body if hasattr(request, "body") else ""
  209. if "x-www-form-urlencoded" in request.content_type:
  210. info = http.QueryDict(body).dict()
  211. if not info:
  212. info = request.GET.dict()
  213. elif "application/json" in request.content_type:
  214. info = json.loads(body) if body else {}
  215. if not info:
  216. info = request.GET.dict()
  217. else:
  218. try:
  219. info = json.loads(body) if body else {}
  220. if not info:
  221. info = request.GET.dict()
  222. except:
  223. info = {}
  224. setattr(request, "json", info)
  225. try:
  226. ret = handler(request, *args, **kwargs)
  227. return ret
  228. except Exception as e:
  229. return to_fail(e)
  230. def yrx_handler(handler, request, is_vauth, *args, **kwargs):
  231. """
  232. 登录session校验
  233. """
  234. req_path = request.META["PATH_INFO"]
  235. ip = request.META.get("HTTP_X_REAL_IP","")
  236. token = request.META.get("HTTP_AUTHORIZATION")
  237. if is_vauth and token:
  238. dectoken = aescbc.decrypt(token)
  239. name = dectoken.split("_")[0]
  240. utype = dectoken.split("_")[1]
  241. if str(utype) == "0":
  242. user = cm.YRXUser.objects.filter(id=name).first()
  243. elif str(utype) == "1":
  244. user = cm.YRXUser.objects.filter(id=name).first()
  245. else:
  246. user = cm.YRXUser.objects.filter(id=name).first()
  247. if not user and False:
  248. #return JsonResponse({"code":403,"data":{}})
  249. return HttpResponse(status=403)
  250. setattr(request, "ip", get_ip(request))
  251. setattr(request, "user", user)
  252. setattr(request, "utype", utype)
  253. if request.method == "OPTIONS":
  254. return JsonResponse({})
  255. body = request.body if hasattr(request, "body") else ""
  256. if "x-www-form-urlencoded" in request.content_type:
  257. info = http.QueryDict(body).dict()
  258. if not info:
  259. info = request.GET.dict()
  260. elif "application/json" in request.content_type:
  261. info = json.loads(body) if body else {}
  262. if not info:
  263. info = request.GET.dict()
  264. else:
  265. try:
  266. info = json.loads(body) if body else {}
  267. if not info:
  268. info = request.GET.dict()
  269. except:
  270. info = {}
  271. setattr(request, "json", info)
  272. try:
  273. ret = handler(request, *args, **kwargs)
  274. return ret
  275. except Exception as e:
  276. return to_fail(e)
  277. def to_suc(data={}):
  278. info = {}
  279. info["data"] = data
  280. info["code"] = 0
  281. return JsonResponse(info,encoder=CusDjangoJSONEncoder)
  282. def to_fail(e=None):
  283. info = {}
  284. info["code"] = 1000
  285. if isinstance(e,ce.TipException):
  286. info["message"] = e.msg
  287. else:
  288. info["message"] = str(e)
  289. return JsonResponse(info)
  290. def tracefail():
  291. traceback.print_exc()
  292. def stream_file(content, content_type, file_name):
  293. """
  294. 输出文件
  295. :param content: 内容 StringIO 类型
  296. :param content_type: 类型 eg: "application/vnd.ms-excel"
  297. :param file_name: 文件名(需指定后缀)
  298. """
  299. response = HttpResponse(content=content, content_type=content_type)
  300. response['Content-Disposition'] = 'attachment; filename={}'.format(file_name)
  301. return response
  302. def get_ip(request):
  303. if request.META.has_key('HTTP_X_REAL_IP'):
  304. ip = request.META['HTTP_X_REAL_IP']
  305. elif request.META.has_key('HTTP_X_FORWARDED_FOR'):
  306. ip = request.META['HTTP_X_FORWARDED_FOR']
  307. else:
  308. ip = request.META['REMOTE_ADDR']
  309. return ip