|
|
@@ -0,0 +1,355 @@
|
|
|
+#coding=utf-8
|
|
|
+'''
|
|
|
+'''
|
|
|
+import json
|
|
|
+import logging
|
|
|
+import re
|
|
|
+import traceback
|
|
|
+import datetime
|
|
|
+import hashlib
|
|
|
+from utils.aestool import aescbc
|
|
|
+
|
|
|
+from django import http
|
|
|
+from django.contrib.sessions.backends.cache import SessionStore
|
|
|
+from django.core.cache import cache
|
|
|
+from django.http import HttpResponse, JsonResponse
|
|
|
+from django.shortcuts import render
|
|
|
+from django.utils.decorators import method_decorator
|
|
|
+from django.views import View
|
|
|
+from django.views.decorators.csrf import csrf_exempt
|
|
|
+from django.core.serializers.json import DjangoJSONEncoder
|
|
|
+
|
|
|
+from common import error_info
|
|
|
+from common.models import UserInfo
|
|
|
+import common.models as cm
|
|
|
+import common.error_info as ce
|
|
|
+
|
|
|
+logger = logging.getLogger(__name__)
|
|
|
+
|
|
|
+
|
|
|
+class CusDjangoJSONEncoder(json.JSONEncoder):
|
|
|
+ """
|
|
|
+ JSONEncoder subclass that knows how to encode date/time, decimal types and UUIDs.
|
|
|
+ """
|
|
|
+ def default(self, o):
|
|
|
+ # See "Date Time String Format" in the ECMA-262 specification.
|
|
|
+ if isinstance(o, datetime.datetime):
|
|
|
+ r = datetime.datetime.strftime(o,'%Y-%m-%d %H:%M:%S')
|
|
|
+ return r
|
|
|
+ elif isinstance(o, datetime.date):
|
|
|
+ return o.isoformat()
|
|
|
+ elif isinstance(o, datetime.time):
|
|
|
+ if is_aware(o):
|
|
|
+ raise ValueError("JSON can't represent timezone-aware times.")
|
|
|
+ r = o.isoformat()
|
|
|
+ if o.microsecond:
|
|
|
+ r = r[:12]
|
|
|
+ return r
|
|
|
+ elif isinstance(o, datetime.timedelta):
|
|
|
+ return duration_iso_string(o)
|
|
|
+ elif isinstance(o, decimal.Decimal):
|
|
|
+ return str(o)
|
|
|
+ elif isinstance(o, uuid.UUID):
|
|
|
+ return str(o)
|
|
|
+ elif isinstance(o, Promise):
|
|
|
+ return six.text_type(o)
|
|
|
+ elif isinstance(o, CallableBool):
|
|
|
+ return bool(o)
|
|
|
+ else:
|
|
|
+ return super(DjangoJSONEncoder, self).default(o)
|
|
|
+
|
|
|
+
|
|
|
+class AuthView(View):
|
|
|
+
|
|
|
+ @method_decorator(csrf_exempt)
|
|
|
+ def dispatch(self, request, *args, **kwargs):
|
|
|
+ """
|
|
|
+ @attention: as_view()方法使用该方法来分发不同http method,添加异常处理及登陆校验
|
|
|
+ """
|
|
|
+ if request.method.lower() in self.http_method_names:
|
|
|
+ handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
|
|
|
+ else:
|
|
|
+ handler = self.http_method_not_allowed
|
|
|
+ return api_wapper(handler, request, True, *args, **kwargs)
|
|
|
+
|
|
|
+class AdminView(View):
|
|
|
+
|
|
|
+ @method_decorator(csrf_exempt)
|
|
|
+ def dispatch(self, request, *args, **kwargs):
|
|
|
+ """
|
|
|
+ @attention: as_view()方法使用该方法来分发不同http method,添加异常处理及登陆校验
|
|
|
+ """
|
|
|
+ self.http_method_names.append("options")
|
|
|
+ if request.method.lower() in self.http_method_names:
|
|
|
+ handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
|
|
|
+ else:
|
|
|
+ handler = self.http_method_not_allowed
|
|
|
+ return admin_handler(handler, request, True, *args, **kwargs)
|
|
|
+
|
|
|
+class YRXView(View):
|
|
|
+
|
|
|
+ @method_decorator(csrf_exempt)
|
|
|
+ def dispatch(self, request, *args, **kwargs):
|
|
|
+ """
|
|
|
+ @attention: as_view()方法使用该方法来分发不同http method,添加异常处理及登陆校验
|
|
|
+ """
|
|
|
+ self.http_method_names.append("options")
|
|
|
+ if request.method.lower() in self.http_method_names:
|
|
|
+ handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
|
|
|
+ else:
|
|
|
+ handler = self.http_method_not_allowed
|
|
|
+ return yrx_handler(handler, request, True, *args, **kwargs)
|
|
|
+
|
|
|
+
|
|
|
+class BaseView(View):
|
|
|
+
|
|
|
+ @method_decorator(csrf_exempt)
|
|
|
+ def dispatch(self, request, *args, **kwargs):
|
|
|
+ """
|
|
|
+ @attention: as_view()方法使用该方法来分发不同http method,添加异常处理及登陆校验
|
|
|
+ """
|
|
|
+ if request.method.lower() in self.http_method_names:
|
|
|
+ handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
|
|
|
+ else:
|
|
|
+ handler = self.http_method_not_allowed
|
|
|
+
|
|
|
+ return api_wapper(handler, request, False, *args, **kwargs)
|
|
|
+
|
|
|
+
|
|
|
+class UploadView(View):
|
|
|
+
|
|
|
+ @method_decorator(csrf_exempt)
|
|
|
+ def dispatch(self, request, *args, **kwargs):
|
|
|
+ """
|
|
|
+ @attention: as_view()方法使用该方法来分发不同http method,添加异常处理及登陆校验
|
|
|
+ """
|
|
|
+ if request.method.lower() in self.http_method_names:
|
|
|
+ handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
|
|
|
+ else:
|
|
|
+ handler = self.http_method_not_allowed
|
|
|
+
|
|
|
+ return upload_wapper(handler,request,True, *args, **kwargs)
|
|
|
+
|
|
|
+
|
|
|
+class InnerView(View):
|
|
|
+
|
|
|
+ @method_decorator(csrf_exempt)
|
|
|
+ def dispatch(self, request, *args, **kwargs):
|
|
|
+ """
|
|
|
+ @attention: as_view()方法使用该方法来分发不同http method,添加异常处理及登陆校验
|
|
|
+ """
|
|
|
+ if request.method.lower() in self.http_method_names:
|
|
|
+ handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
|
|
|
+ if request.META.get("HTTP_TOKEN") != "7dpHIhpweckghdoSvrXwMftcjZRIzKwJ":
|
|
|
+ handler = self.http_method_not_allowed
|
|
|
+ else:
|
|
|
+ handler = self.http_method_not_allowed
|
|
|
+
|
|
|
+ return api_wapper(handler, request, False, *args, **kwargs)
|
|
|
+
|
|
|
+
|
|
|
+def show_history(request):
|
|
|
+ logined_history = cache.get("logined_history", {})
|
|
|
+ for k, v in logined_history.iteritems():
|
|
|
+ logger.info("k: %s, v: %s", str(k), str(v))
|
|
|
+ logger.info("current session: %s", str(request.session.session_key))
|
|
|
+ ss = SessionStore(request.session.session_key)
|
|
|
+ for k, v in ss.iteritems():
|
|
|
+ logger.info("k: %s, v: %s", str(k), str(v))
|
|
|
+
|
|
|
+
|
|
|
+def api_wapper(handler, request, is_vauth, *args, **kwargs):
|
|
|
+ """
|
|
|
+ @attention: 调试API时使用的装饰器
|
|
|
+ """
|
|
|
+ req_path = request.META["PATH_INFO"]
|
|
|
+ ip = request.META.get("HTTP_X_REAL_IP","")
|
|
|
+ token = request.META.get("HTTP_AUTHORIZATION")
|
|
|
+ if is_vauth:
|
|
|
+ if token:
|
|
|
+ dec_name = aescbc.decrypt(token)
|
|
|
+ name = dec_name.split("_")[0]
|
|
|
+ utype = dec_name.split("_")[1]
|
|
|
+ if utype == 1:
|
|
|
+ user = cm.Goverment.objects.filter(id=name).first()
|
|
|
+ elif utype == 2:
|
|
|
+ user = cm.EnterPrise.objects.filter(id=name).first()
|
|
|
+ else:
|
|
|
+ user = cm.StaffUser.objects.filter(id=name).first()
|
|
|
+ if not user and False:
|
|
|
+ return JsonResponse({"code":403,"data":{}})
|
|
|
+ #return HttpResponse(status=403)
|
|
|
+
|
|
|
+ setattr(request, "ip", get_ip(request))
|
|
|
+ setattr(request, "user", user)
|
|
|
+ setattr(request, "utype", utype)
|
|
|
+ if request.method == "OPTIONS":
|
|
|
+ return JsonResponse({})
|
|
|
+ else:
|
|
|
+ return JsonResponse({"code":403,"data":{}})
|
|
|
+
|
|
|
+ body = request.body if hasattr(request, "body") else ""
|
|
|
+ if "x-www-form-urlencoded" in request.content_type:
|
|
|
+ info = http.QueryDict(body).dict()
|
|
|
+ if not info:
|
|
|
+ info = request.GET.dict()
|
|
|
+ elif "application/json" in request.content_type:
|
|
|
+ info = json.loads(body) if body else {}
|
|
|
+ if not info:
|
|
|
+ info = request.GET.dict()
|
|
|
+ else:
|
|
|
+ try:
|
|
|
+ info = json.loads(body) if body else {}
|
|
|
+ if not info:
|
|
|
+ info = request.GET.dict()
|
|
|
+ except:
|
|
|
+ info = {}
|
|
|
+ setattr(request, "json", info)
|
|
|
+
|
|
|
+ try:
|
|
|
+ ret = handler(request, *args, **kwargs)
|
|
|
+ return ret
|
|
|
+ except Exception as e:
|
|
|
+ return to_fail(e)
|
|
|
+
|
|
|
+def admin_handler(handler, request, is_vauth, *args, **kwargs):
|
|
|
+ """
|
|
|
+ 登录session校验
|
|
|
+ """
|
|
|
+ req_path = request.META["PATH_INFO"]
|
|
|
+ ip = request.META.get("HTTP_X_REAL_IP","")
|
|
|
+ token = request.META.get("HTTP_AUTHORIZATION")
|
|
|
+ if is_vauth and token:
|
|
|
+ dectoken = aescbc.decrypt(token)
|
|
|
+ name = dectoken.split("_")[0]
|
|
|
+ utype = dectoken.split("_")[1]
|
|
|
+ if str(utype) == "0":
|
|
|
+ user = UserInfo.objects.filter(id=name).first()
|
|
|
+ elif str(utype) == "1":
|
|
|
+ user = cm.Goverment.objects.filter(id=name).first()
|
|
|
+ else:
|
|
|
+ user = cm.EnterPrise.objects.filter(id=name).first()
|
|
|
+ if not user and False:
|
|
|
+ #return JsonResponse({"code":403,"data":{}})
|
|
|
+ return HttpResponse(status=403)
|
|
|
+
|
|
|
+ setattr(request, "ip", get_ip(request))
|
|
|
+ setattr(request, "user", user)
|
|
|
+ setattr(request, "utype", utype)
|
|
|
+ if request.method == "OPTIONS":
|
|
|
+ return JsonResponse({})
|
|
|
+
|
|
|
+ body = request.body if hasattr(request, "body") else ""
|
|
|
+ if "x-www-form-urlencoded" in request.content_type:
|
|
|
+ info = http.QueryDict(body).dict()
|
|
|
+ if not info:
|
|
|
+ info = request.GET.dict()
|
|
|
+ elif "application/json" in request.content_type:
|
|
|
+ info = json.loads(body) if body else {}
|
|
|
+ if not info:
|
|
|
+ info = request.GET.dict()
|
|
|
+ else:
|
|
|
+ try:
|
|
|
+ info = json.loads(body) if body else {}
|
|
|
+ if not info:
|
|
|
+ info = request.GET.dict()
|
|
|
+ except:
|
|
|
+ info = {}
|
|
|
+
|
|
|
+ setattr(request, "json", info)
|
|
|
+
|
|
|
+ try:
|
|
|
+ ret = handler(request, *args, **kwargs)
|
|
|
+ return ret
|
|
|
+ except Exception as e:
|
|
|
+ return to_fail(e)
|
|
|
+
|
|
|
+def yrx_handler(handler, request, is_vauth, *args, **kwargs):
|
|
|
+ """
|
|
|
+ 登录session校验
|
|
|
+ """
|
|
|
+ req_path = request.META["PATH_INFO"]
|
|
|
+ ip = request.META.get("HTTP_X_REAL_IP","")
|
|
|
+ token = request.META.get("HTTP_AUTHORIZATION")
|
|
|
+ if is_vauth and token:
|
|
|
+ dectoken = aescbc.decrypt(token)
|
|
|
+ name = dectoken.split("_")[0]
|
|
|
+ utype = dectoken.split("_")[1]
|
|
|
+ if str(utype) == "0":
|
|
|
+ user = cm.YRXUser.objects.filter(id=name).first()
|
|
|
+ elif str(utype) == "1":
|
|
|
+ user = cm.YRXUser.objects.filter(id=name).first()
|
|
|
+ else:
|
|
|
+ user = cm.YRXUser.objects.filter(id=name).first()
|
|
|
+ if not user and False:
|
|
|
+ #return JsonResponse({"code":403,"data":{}})
|
|
|
+ return HttpResponse(status=403)
|
|
|
+
|
|
|
+ setattr(request, "ip", get_ip(request))
|
|
|
+ setattr(request, "user", user)
|
|
|
+ setattr(request, "utype", utype)
|
|
|
+ if request.method == "OPTIONS":
|
|
|
+ return JsonResponse({})
|
|
|
+
|
|
|
+ body = request.body if hasattr(request, "body") else ""
|
|
|
+ if "x-www-form-urlencoded" in request.content_type:
|
|
|
+ info = http.QueryDict(body).dict()
|
|
|
+ if not info:
|
|
|
+ info = request.GET.dict()
|
|
|
+ elif "application/json" in request.content_type:
|
|
|
+ info = json.loads(body) if body else {}
|
|
|
+ if not info:
|
|
|
+ info = request.GET.dict()
|
|
|
+ else:
|
|
|
+ try:
|
|
|
+ info = json.loads(body) if body else {}
|
|
|
+ if not info:
|
|
|
+ info = request.GET.dict()
|
|
|
+ except:
|
|
|
+ info = {}
|
|
|
+
|
|
|
+ setattr(request, "json", info)
|
|
|
+
|
|
|
+ try:
|
|
|
+ ret = handler(request, *args, **kwargs)
|
|
|
+ return ret
|
|
|
+ except Exception as e:
|
|
|
+ return to_fail(e)
|
|
|
+
|
|
|
+def to_suc(data={}):
|
|
|
+ info = {}
|
|
|
+ info["data"] = data
|
|
|
+ info["code"] = 0
|
|
|
+ return JsonResponse(info,encoder=CusDjangoJSONEncoder)
|
|
|
+
|
|
|
+def to_fail(e=None):
|
|
|
+ info = {}
|
|
|
+ info["code"] = 1000
|
|
|
+ if isinstance(e,ce.TipException):
|
|
|
+ info["message"] = e.msg
|
|
|
+ else:
|
|
|
+ info["message"] = str(e)
|
|
|
+ return JsonResponse(info)
|
|
|
+
|
|
|
+def tracefail():
|
|
|
+ traceback.print_exc()
|
|
|
+
|
|
|
+def stream_file(content, content_type, file_name):
|
|
|
+ """
|
|
|
+ 输出文件
|
|
|
+ :param content: 内容 StringIO 类型
|
|
|
+ :param content_type: 类型 eg: "application/vnd.ms-excel"
|
|
|
+ :param file_name: 文件名(需指定后缀)
|
|
|
+ """
|
|
|
+ response = HttpResponse(content=content, content_type=content_type)
|
|
|
+ response['Content-Disposition'] = 'attachment; filename={}'.format(file_name)
|
|
|
+ return response
|
|
|
+
|
|
|
+def get_ip(request):
|
|
|
+ if request.META.has_key('HTTP_X_REAL_IP'):
|
|
|
+ ip = request.META['HTTP_X_REAL_IP']
|
|
|
+ elif request.META.has_key('HTTP_X_FORWARDED_FOR'):
|
|
|
+ ip = request.META['HTTP_X_FORWARDED_FOR']
|
|
|
+ else:
|
|
|
+ ip = request.META['REMOTE_ADDR']
|
|
|
+ return ip
|