예제 #1
0
 def post(self, request):
     """
     新增项目
     :param request:
     :return:
     """
     data = JSONParser().parse(request)
     result = self.parameter_check(data)
     if result:
         return result
     data['user'] = request.user.pk
     project_serializer = ProjectDeserializer(data=data)
     try:
         Project.objects.get(name=data['name'])
         return JsonResponse(code='1002', msg='存在相同的项目名称!')
     except ObjectDoesNotExist:
         with transaction.atomic():
             if project_serializer.is_valid():
                 # 保存项目
                 project_serializer.save()
                 # 记录动态
                 record_dynamic(project=project_serializer.data.get("id"),
                                _type='添加',
                                operationObject='项目',
                                user=request.user.pk,
                                data=data['name'])
                 # 创建项目的用户添加为该项目的成员
                 self.add_project_member(project_serializer.data.get('id'),
                                         request.user.pk)
                 return JsonResponse(
                     data={'project_id': project_serializer.data.get('id')},
                     code='0',
                     msg='新增项目成功!')
             else:
                 return JsonResponse(code='1001', msg='新增项目失败!')
예제 #2
0
 def post(self, request):
     """
     启用项目
     :param request:
     :return:
     """
     data = JSONParser().parse(request)
     result = self.parameter_check(data)
     if result:
         return result
     # 检查项目是否存在
     try:
         obj = Project.objects.get(id=data['project_id'])
         if not request.user.is_superuser and obj.user.is_superuser:
             return JsonResponse(code='1019', msg=str(obj) + '无权限操作该项目!')
         obj.status = True
         obj.save()
         record_dynamic(project=data['project_id'],
                        _type='禁用',
                        operationObject='项目',
                        user=request.user.pk,
                        data=obj.name)
         return JsonResponse(code='0', msg='启用成功')
     except ObjectDoesNotExist:
         return JsonResponse(code='1004', msg='项目不存在!')
예제 #3
0
 def get(self, request):
     """
     获取项目列表
     :param request:
     :return:
     """
     try:
         page_size = int(request.GET.get("page_size", 20))
         page = int(request.GET.get("page", 1))
     except (TypeError, ValueError):
         return JsonResponse(code="1014", msg="页数必须为整数!")
     name = request.GET.get("name")
     if name:
         obj = Project.objects.filter(name__contains=name).order_by("id")
     else:
         obj = Project.objects.all().order_by("id")
     paginator = Paginator(obj, page_size)  # paginator对象
     total = paginator.num_pages  # 总页数
     try:
         obm = paginator.page(page)
     except PageNotAnInteger:
         obm = paginator.page(1)
     except EmptyPage:
         obm = paginator.page(paginator.num_pages)
     serialize = ProjectSerializer(obm, many=True)
     return JsonResponse(data={
         "data": serialize.data,
         "page": page,
         "total": total
     },
                         code="0",
                         msg="查询成功")
예제 #4
0
 def post(self, request):
     """
     删除项目
     :param request:
     :return:
     """
     data = JSONParser().parse(request)
     result = self.parameter_check(data)
     print(data['ids'])
     if result:
         return result
     try:
         for i in data['ids']:
             try:
                 obj = Project.objects.get(id=i)
                 if not request.user.is_superuser and obj.user.is_superuser:
                     return JsonResponse(code='1019',
                                         msg=str(obj) + '无权限操作该项目!')
             except ObjectDoesNotExist:
                 return JsonResponse(code='1004', msg='项目不存在!')
         for j in data['ids']:
             obj = Project.objects.filter(id=j)
             obj.delete()
             my_user_cron = CronTab(user=True)
             my_user_cron.remove_all(comment=j)
             my_user_cron.write()
         return JsonResponse(code='0', msg='删除项目成功!')
     except ObjectDoesNotExist:
         return JsonResponse(code='1004', msg='项目不存在!')
예제 #5
0
 def parameter_check(self, data):
     """
     校验参数
     :param data:
     :return:
     """
     try:
         # 必传参数 success
         if data["success"] not in [0, 1]:
             return JsonResponse(code="999996", msg="参数有误!")
     except KeyError:
         return JsonResponse(code="999996", msg="参数有误!")
예제 #6
0
    def parameter_check(self, data):
        """
        校验参数
        :param data:
        :return:
        """
        try:
            # 校验project_id类型为int
            if not isinstance(data['project_id'], int):
                return JsonResponse(code='1018', msg='项目id为整数!')

        except KeyError:
            return JsonResponse(code='1018', msg='项目id为整数!')
예제 #7
0
 def parameter_check(self, data):
     """
     验证参数
     :param data:
     :return:
     """
     try:
         # 必填参数name, version, type
         if not data["name"] or not data["version"] or not data["type"]:
             return JsonResponse(code="1016", msg="必填参数不能为空!")
         # type 类型web,APP
         if data["type"] not in ['Web', 'App']:
             return JsonResponse(code="1017", msg='类型错误!')
     except KeyError:
         return JsonResponse(code="1003", msg='参数有误!')
 def parameter_check(self, data):
     """
     验证参数
     :param data:
     :return:
     """
     try:
         # 校验project_id类型为int
         if not isinstance(data['project_id'], int):
             return JsonResponse(code='1018', msg='项目id为整数!')
         # name, host为必填
         if not data["name"] or not data['host']:
             return JsonResponse(code="1016", msg="必填参数不能为空!")
     except KeyError:
         return JsonResponse(code="1003", msg='参数有误!')
예제 #9
0
    def paramter_check(self, data):
        """
        校验参数
        :param data:
        :return:
        """

        try:
            # 校验project_id类型为int
            if not isinstance(data['project_id'], int):
                return JsonResponse(code='1018', msg='项目id为整数!')
            # 必传参数name,version,type
            if not data['name'] or not ['version'] or not data['type']:
                return JsonResponse(code="1016", msg="必填参数不能为空!")
            # type 类型web,APP
            if data["type"] not in ['Web', 'App']:
                return JsonResponse(code="1017", msg='类型错误!')
        except KeyError:
            return JsonResponse(code="1003", msg='参数有误!')
 def get(self, request):
     """
     获取host列表
     :param request:
     :return:
     """
     try:
         page_size = int(request.GET.get("page_size", 20))
         page = int(request.GET.get("page", 1))
     except (TypeError, ValueError):
         return JsonResponse(code="1014", msg="页数必须为整数!")
     project_id = request.GET.get("project_id")
     if not project_id.isdecimal():
         return JsonResponse(code='1003', msg='参数有误!')
     try:
         pro_data = Project.objects.get(id=project_id)
     except ObjectDoesNotExist:
         return JsonResponse(code='1004', msg='项目不存在!')
     pro_data = ProjectSerializer(pro_data)
     if not pro_data.data['status']:
         return JsonResponse(code='1020', msg='该项目已禁用!')
     name = request.GET.get('name')
     if name:
         obj = GlobalHost.objects.filter(name__contains=name,
                                         project=project_id).order_by('id')
     else:
         obj = GlobalHost.objects.filter(project=project_id).order_by('id')
     paginator = Paginator(obj, page_size)  # paginator对象
     total = paginator.num_pages  # 总页数
     try:
         obm = paginator.page(page)
     except PageNotAnInteger:
         obm = paginator.page(1)
     except EmptyPage:
         obm = paginator.page(paginator.num_pages)
     serialize = GlobalHostSerializer(obm, many=True)
     return JsonResponse(data={
         "data": serialize.data,
         "page": page,
         "total": total
     },
                         code="0",
                         msg="查询成功")
예제 #11
0
 def get(self, request):
     """
     获取项目详情
     :param request:
     :return:
     """
     project_id = request.GET.get("project_id")
     if not project_id:
         return JsonResponse(code='1018', msg='项目id为整数!')
     if not project_id.isdecimal():
         return JsonResponse(code='1003', msg='参数有误!')
     # 查找项目是否存在
     try:
         obj = Project.objects.get(id=project_id)
     except ObjectDoesNotExist:
         return JsonResponse(code='1004', msg='项目不存在!')
     serialize = ProjectSerializer(obj)
     if serialize.data['status']:
         return JsonResponse(code='0', msg='获取成功!', data=serialize.data)
     else:
         return JsonResponse(code='1020', msg='该项目已禁用!')
예제 #12
0
 def post(self, request):
     """
     修改项目
     :param request:
     :return:
     """
     data = JSONParser().parse(request)
     result = self.paramter_check(data)
     if result:
         return result
     # 查找项目是否存在
     try:
         obj = Project.objects.get(id=data['project_id'])
         if not request.user.is_superuser and obj.user.is_superuser:
             return JsonResponse(code='1019', msg='无该项目操作权限!')
     except ObjectDoesNotExist:
         return JsonResponse(code='1004', msg='项目不存在!')
     # 查找是否存在相同名称的项目
     pro_name = Project.objects.filter(name=data['name']).exclude(
         id=data['project_id'])
     if len(pro_name):
         return JsonResponse(code='1005', msg='项目已存在')
     else:
         serializer = ProjectDeserializer(data=data)
         with transaction.atomic():
             if serializer.is_valid():
                 # 修改项目
                 serializer.update(instance=obj, validated_data=data)
                 # 记录动态
                 record_dynamic(project=data['project_id'],
                                _type='修改',
                                operationObject='项目',
                                user=request.user.pk,
                                data=data['name'])
                 return JsonResponse(code='0', msg='修改项目成功!')
             else:
                 return JsonResponse(code='1001', msg='修改项目失败!')
 def post(self, request):
     """
     新增host
     :param request:
     :return:
     """
     data = JSONParser().parse(request)
     result = self.parameter_check(data)
     if result:
         return result
     try:
         obj = Project.objects.get(id=data['project_id'])
         if not request.user.is_superuser and obj.user.is_superuser:
             return JsonResponse(code='1019', msg='无该项目操作权限!')
     except ObjectDoesNotExist:
         return JsonResponse(code='1004', msg='项目不存在!')
     pro_data = ProjectSerializer(obj)
     if not pro_data.data['status']:
         return JsonResponse(code='1020', msg='该项目已禁用!')
     obi = GlobalHost.objects.filter(name=data['name'],
                                     project=data['project_id'])
     if obi:
         return JsonResponse(code='1006', msg='host已存在!')
     else:
         serializer = GlobalHostSerializer(data=data)
         with transaction.atomic():
             if serializer.is_valid():
                 # 外键project_id
                 serializer.save(project=obj)
                 # 记录动态
                 record_dynamic(project=data['project_id'],
                                _type='添加',
                                operationObject='域名',
                                user=request.user.pk,
                                data=data['name'])
                 return JsonResponse(
                     data={'host_id': serializer.data.get('id')},
                     code='0',
                     msg='创建成功!')
             return JsonResponse(code='1001', msg='创建失败!')
예제 #14
0
    def post(self, request):
        """
        记录访客
        :param request:
        :return:
        """
        if request.environ["REMOTE_ADDR"] == "127.0.0.1":
            return JsonResponse(code="999999", msg="成功!")
        data = JSONParser().parse(request)
        result = self.parameter_check(data)
        if result:
            return result
        if data["success"] == 0:
            ip = self.ip_get_city(request.environ["REMOTE_ADDR"])
            VisitorsRecord(formattedAddress=request.environ["REMOTE_ADDR"],
                           province=ip["province"],
                           city=ip["city"],
                           success="失败",
                           reason="获取用户经纬度失败!").save()
        else:
            try:
                longitude = data["longitude"]
                latitude = data["latitude"]
            except KeyError:
                return JsonResponse(code="999996", msg="参数有误")
            params = {
                "output": "json",
                # "location": "104.06151"+","+"30.54852",
                "key": "2200d7985fd43582411687abaa5b01eb",
                "location": str(longitude) + "," + str(latitude)
            }
            headers = {"Content-Type": "application/json;charset=utf-8"}
            response = requests.get(
                url="http://restapi.amap.com/v3/geocode/regeo",
                params=params,
                headers=headers,
                allow_redirects=False,
                timeout=8)
            if response.status_code == 301:
                response = requests.get(url=response.headers["location"])
            try:
                visitor_addr = response.json()
                if visitor_addr["status"] == "1":
                    VisitorsRecord(
                        formattedAddress=visitor_addr["regeocode"]
                        ["formatted_address"],
                        country=visitor_addr["regeocode"]["addressComponent"]
                        ["country"],
                        province=visitor_addr["regeocode"]["addressComponent"]
                        ["province"],
                        city=visitor_addr["regeocode"]["addressComponent"]
                        ["city"],
                        district=visitor_addr["regeocode"]["addressComponent"]
                        ["district"],
                        township=visitor_addr["regeocode"]["addressComponent"]
                        ["township"],
                        street=visitor_addr["regeocode"]["addressComponent"]
                        ["streetNumber"]["street"],
                        number=visitor_addr["regeocode"]["addressComponent"]
                        ["streetNumber"]["number"],
                        success="成功",
                        reason=visitor_addr["info"]).save()
                else:
                    ip = self.ip_get_city(request.environ["REMOTE_ADDR"])
                    VisitorsRecord(
                        formattedAddress=request.environ["REMOTE_ADDR"],
                        province=ip["province"],
                        city=ip["city"],
                        success="失败",
                        reason=ip["info"]).save()
            except Exception as e:
                ip = self.ip_get_city(request.environ["REMOTE_ADDR"])
                VisitorsRecord(formattedAddress=request.environ["REMOTE_ADDR"],
                               province=ip["province"],
                               city=ip["city"],
                               success="失败",
                               reason=e).save()

        return JsonResponse(code="999999", msg="成功!")