Esempio n. 1
0
    def post(self, request):
        """
        添加用例
        """
        # data = JSONParser().parse(request)
        # case_serializer = CaseSerializer(data=data)
        # print(case_serializer)
        # with transaction.atomic():
        #     if case_serializer.is_valid():
        #         case_serializer.save()
        #         return JsonResponse(data={
        #             "case_id": case_serializer.data.get("id")
        #         }, code="999999", msg="成功")
        #     else:
        #         return JsonResponse(code="999998", msg="失败")

        data = JSONParser().parse(request)
        # obj = Project.objects.get(id=data["project_id"])
        # api_name = ApiInfo.objects.filter(name=data["name"],project=data["project_id"])  # 没有传递project id 过来
        # if len(api_name):
        #     return JsonResponse(code="999997", msg="用例名已存在,请更改")
        # else:
        with transaction.atomic():  # 执行错误后,帮助事务回滚
            serialize = ApiInfoDeserializer(data=data)
            # print(serialize)
            if serialize.is_valid():
                serialize.save()
                # print(serialize.validated_data)
                api_id = serialize.data.get("id")
                if len(data.get("headDict")):
                    for i in data["headDict"]:
                        i["api"] = api_id
                        head_serialize = ApiHeadDeserializer(data=i)
                        if head_serialize.is_valid():
                            head_serialize.save(api=ApiInfo.objects.get(
                                id=api_id))
                if len(data.get("requestList")):
                    # print("###################")
                    # print(type(data["requestList"]))
                    for i in data["requestList"]:
                        if i.get("name"):
                            i["api"] = api_id
                            param_serialize = ApiParameterDeserializer(data=i)
                            if param_serialize.is_valid():
                                param_serialize.save(api=ApiInfo.objects.get(
                                    id=api_id))
                if len(data.get("responseList")):
                    for i in data["responseList"]:
                        if i.get("name"):
                            i["api"] = api_id
                            response_serialize = ApiResponseDeserializer(
                                data=i)
                            if response_serialize.is_valid():
                                response_serialize.save(
                                    api=ApiInfo.objects.get(id=api_id))
                return JsonResponse(code="999999",
                                    msg="成功!",
                                    data={"api_id": api_id})
            print(serialize.errors)
            return JsonResponse(code="999996", msg="参数有误!")
Esempio n. 2
0
 def addApi(data):
     with transaction.atomic():  # 执行错误后,帮助事物回滚
         try:
             serialize = ApiInfoDeserializer(data=data)
             if serialize.is_valid():
                 try:
                     obj = Project.objects.get(id=data["project_id"])
                     obi = ApiGroupLevelFirst.objects.get(
                         id=data["apiGroupLevelFirst_id"],
                         project=data["project_id"])
                     serialize.save(project=obj, apiGroupLevelFirst=obi)
                 except KeyError:
                     serialize.save(project=obj)
                 api_id = serialize.data.get("id")
                 data["id"] = api_id
                 if "headDict" in data and len(data.get("headDict")) > 0:
                     for i in data["headDict"]:
                         if i.get("name"):
                             i["api"] = api_id
                             head_serialize = ApiHeadDeserializer(data=i)
                             if head_serialize.is_valid():
                                 head_serialize.save(
                                     api=ApiInfo.objects.get(id=api_id))
                 if data["requestParameterType"] in (
                         "application/x-www-form-urlencoded",
                         "application/json", "text/plain"):
                     if "requestList" in data and len(
                             data.get("requestList")):
                         for i in data["requestList"]:
                             if i.get("name"):
                                 i["api"] = api_id
                                 param_serialize = ApiParameterDeserializer(
                                     data=i)
                                 if param_serialize.is_valid():
                                     param_serialize.save(
                                         api=ApiInfo.objects.get(id=api_id))
                 else:
                     if "requestList" in data and len(
                             data.get("requestList")):
                         ApiParameterRaw(api=ApiInfo.objects.get(id=api_id),
                                         data=data["requestList"]).save()
                 if "responseList" in data and len(
                         data.get("responseList")):
                     for i in data["responseList"]:
                         if i.get("name"):
                             i["api"] = api_id
                             response_serialize = ApiResponseDeserializer(
                                 data=i)
                             if response_serialize.is_valid():
                                 response_serialize.save(
                                     api=ApiInfo.objects.get(id=api_id))
                 return data
             else:
                 print("添加接口[%s]出现异常: %s" % (data["name"], serialize.error))
                 return None
         except:
             logging.error(traceback.format_exc())
Esempio n. 3
0
 def get(self, request):
     """
     获取用例接口参数
     """
     try:
         page_size = int(request.GET.get("page_size", 20))
         page = int(request.GET.get("page", 1))
     except (TypeError, ValueError):
         return JsonResponse(code="999985",
                             msg="page and page_size must be integer!")
     obi = ApiInfo.objects.all().order_by("id")
     paginator = Paginator(obi, page_size)  # paginator对象
     total = paginator.num_pages  # 总页数
     obm = paginator.page(page)
     serialize = ApiInfoDeserializer(obm, many=True)
     return JsonResponse(data={
         "data": serialize.data,
         "page": page,
         "total": total
     },
                         code="999999",
                         msg="成功")
Esempio n. 4
0
 def post(self, request):
     """
     修改接口
     :param request:
     :return:
     """
     data = JSONParser().parse(request)
     result = self.parameter_check(data)
     if result:
         return result
     data["userUpdate"] = request.user.pk
     try:
         pro_data = Project.objects.get(id=data["project_id"])
     except ObjectDoesNotExist:
         return JsonResponse(code="999995", msg="项目不存在!")
     pro_data = ProjectSerializer(pro_data)
     if not pro_data.data["status"]:
         return JsonResponse(code="999985", msg="该项目已禁用")
     api_name = ApiInfo.objects.filter(name=data["name"], project=data["project_id"]).exclude(id=data["id"])
     if len(api_name):
         return JsonResponse(code="999997", msg="存在相同名称!")
     try:
         obi = ApiInfo.objects.get(id=data["id"])
     except ObjectDoesNotExist:
         return JsonResponse(code="999990", msg="接口不存在!")
     with transaction.atomic():
         try:
             serialize = ApiInfoDeserializer(data=data)
             if serialize.is_valid():
                 data["userUpdate"] = request.user
                 try:
                     if not isinstance(data["apiGroupLevelFirst_id"], int):
                         return JsonResponse(code="999996", msg="参数有误!")
                     ApiGroupLevelFirst.objects.get(id=data["apiGroupLevelFirst_id"], project=data["project_id"])
                     User.objects.get(id=request.user.pk)
                     serialize.update(instance=obi, validated_data=data)
                 except KeyError:
                     User.objects.get(id=request.user.pk)
                     serialize.update(instance=obi, validated_data=data)
                 try:
                     ApiHead.objects.filter(api=data["id"]).delete()
                     if len(data["headDict"]):
                         for i in data["headDict"]:
                             try:
                                 if i["name"]:
                                     i["api"] = data['id']
                                     head_serialize = ApiHeadDeserializer(data=i)
                                     if head_serialize.is_valid():
                                         head_serialize.save(api=ApiInfo.objects.get(id=data["id"]))
                             except KeyError:
                                 return JsonResponse(code="999996", msg="参数有误!")
                 except KeyError:
                     pass
                 ApiParameter.objects.filter(api=data["id"]).delete()
                 ApiParameterRaw.objects.filter(api=data["id"]).delete()
                 if data["requestParameterType"] == "form-data":
                     try:
                         if len(data["requestList"]):
                             for i in data["requestList"]:
                                 try:
                                     if i["name"]:
                                         i["api"] = data['id']
                                         param_serialize = ApiParameterDeserializer(data=i)
                                         if param_serialize.is_valid():
                                             param_serialize.save(api=ApiInfo.objects.get(id=data["id"]))
                                         else:
                                             return JsonResponse(code="999998", msg="失败!")
                                 except KeyError:
                                     return JsonResponse(code="999996", msg="参数有误!")
                     except KeyError:
                         pass
                 else:
                     try:
                         if len(data["requestList"]):
                             ApiParameterRaw(api=ApiInfo.objects.get(id=data['id']), data=data["requestList"]).save()
                     except KeyError:
                         pass
                 try:
                     ApiResponse.objects.filter(api=data["id"]).delete()
                     if len(data["responseList"]):
                         for i in data["responseList"]:
                             try:
                                 if i["name"]:
                                     i["api"] = data['id']
                                     response_serialize = ApiResponseDeserializer(data=i)
                                     if response_serialize.is_valid():
                                         response_serialize.save(api=ApiInfo.objects.get(id=data['id']))
                                     else:
                                         return JsonResponse(code="999998", msg="失败!")
                             except KeyError:
                                 return JsonResponse(code="999998", msg="失败!")
                 except KeyError:
                     pass
                 record_dynamic(project=data["project_id"],
                                _type="新增", operationObject="接口", user=request.user.pk,
                                data="新增接口“%s”" % data["name"])
                 api_record = ApiOperationHistory(api=ApiInfo.objects.get(id=data['id']),
                                                  user=User.objects.get(id=request.user.pk),
                                                  description="新增接口\"%s\"" % data["name"])
                 api_record.save()
                 return JsonResponse(code="999999", msg="成功!")
             return JsonResponse(code="999998", msg="失败!")
         except ObjectDoesNotExist:
             return JsonResponse(code="999991", msg="分组不存在!")
Esempio n. 5
0
 def post(self, request):
     """
     新增接口
     :param request:
     :return:
     """
     data = JSONParser().parse(request)
     result = self.parameter_check(data)
     if result:
         return result
     data["userUpdate"] = request.user.pk
     try:
         obj = Project.objects.get(id=data["project_id"])
         if not request.user.is_superuser and obj.user.is_superuser:
             return JsonResponse(code="999983", msg="无操作权限!")
     except ObjectDoesNotExist:
         return JsonResponse(code="999995", msg="项目不存在!")
     pro_data = ProjectSerializer(obj)
     if not pro_data.data["status"]:
         return JsonResponse(code="999985", msg="该项目已禁用")
     api_name = ApiInfo.objects.filter(name=data["name"], project=data["project_id"])
     if len(api_name):
         return JsonResponse(code="999997", msg="存在相同名称!")
     else:
         with transaction.atomic(): # 执行错误后,帮助事物回滚
             try:
                 serialize = ApiInfoDeserializer(data=data)
                 if serialize.is_valid():
                     try:
                         if not isinstance(data["apiGroupLevelFirst_id"], int):
                             return JsonResponse(code="999996", msg="参数有误!")
                         obi = ApiGroupLevelFirst.objects.get(id=data["apiGroupLevelFirst_id"], project=data["project_id"])
                         serialize.save(project=obj, apiGroupLevelFirst=obi)
                     except KeyError:
                         serialize.save(project=obj)
                     api_id = serialize.data.get("id")
                     try:
                         if len(data["headDict"]):
                             for i in data["headDict"]:
                                 try:
                                     if i["name"]:
                                         i["api"] = api_id
                                         head_serialize = ApiHeadDeserializer(data=i)
                                         if head_serialize.is_valid():
                                             head_serialize.save(api=ApiInfo.objects.get(id=api_id))
                                 except KeyError:
                                     return JsonResponse(code="999996", msg="参数有误!")
                     except KeyError:
                         pass
                     if data["requestParameterType"] == "form-data":
                         try:
                             if len(data["requestList"]):
                                 for i in data["requestList"]:
                                     try:
                                         if i["name"]:
                                             i["api"] = api_id
                                             param_serialize = ApiParameterDeserializer(data=i)
                                             if param_serialize.is_valid():
                                                 param_serialize.save(api=ApiInfo.objects.get(id=api_id))
                                             else:
                                                 return JsonResponse(code="999998", msg="失败!")
                                     except KeyError:
                                         return JsonResponse(code="999996", msg="参数有误!")
                         except KeyError:
                             pass
                     else:
                         try:
                             if len(data["requestList"]):
                                 ApiParameterRaw(api=ApiInfo.objects.get(id=api_id), data=data["requestList"]).save()
                         except KeyError:
                             pass
                     try:
                         if len(data["responseList"]):
                             for i in data["responseList"]:
                                 try:
                                     if i["name"]:
                                         i["api"] = api_id
                                         response_serialize = ApiResponseDeserializer(data=i)
                                         if response_serialize.is_valid():
                                             response_serialize.save(api=ApiInfo.objects.get(id=api_id))
                                         else:
                                             return JsonResponse(code="999998", msg="失败!")
                                 except KeyError:
                                     logging.exception("Error")
                                     return JsonResponse(code="999998", msg="失败!")
                     except KeyError:
                         pass
                     record_dynamic(project=data["project_id"],
                                    _type="新增", operationObject="接口", user=request.user.pk,
                                    data="新增接口“%s”" % data["name"])
                     api_record = ApiOperationHistory(api=ApiInfo.objects.get(id=api_id),
                                                      user=User.objects.get(id=request.user.pk),
                                                      description="新增接口“%s”" % data["name"])
                     api_record.save()
                     return JsonResponse(code="999999", msg="成功!", data={"api_id": api_id})
                 return JsonResponse(code="999998", msg="失败!")
             except ObjectDoesNotExist:
                 return JsonResponse(code="999991", msg="分组不存在!")
Esempio n. 6
0
def add_swagger_api(data, user):
    """
    swagger接口写入数据库
    :param data:  json数据
    :param user:  用户model
    :return:
    """
    try:
        obj = Project.objects.get(id=data["project_id"])
        try:
            with transaction.atomic():  # 执行错误后,帮助事物回滚
                serialize = ApiInfoDeserializer(data=data)
                if serialize.is_valid():
                    serialize.save(project=obj)
                    api_id = serialize.data.get("id")
                    # print('*'*8)
                    # print(t(data.get("headDict")))
                    if len(data.get("headDict")) > 0:
                        for i in data["headDict"]:
                            if i.get("name"):
                                i["api"] = api_id
                                head_serialize = ApiHeadDeserializer(data=i)
                                if head_serialize.is_valid():
                                    head_serialize.save(
                                        api=ApiInfo.objects.get(id=api_id))

                    if data["requestParameterType"] == "form-data":
                        if len(data.get("requestList")):
                            for i in data["requestList"]:
                                if i.get("name"):
                                    i["api"] = api_id
                                    param_serialize = ApiParameterDeserializer(
                                        data=i)
                                    if param_serialize.is_valid():
                                        param_serialize.save(
                                            api=ApiInfo.objects.get(id=api_id))
                    # else:
                    #     if len(data.get("requestList")):
                    #         ApiParameterRaw(api=ApiInfo.objects.get(id=api_id), data=data["requestList"].replace("'", "\"")).save()
                    if len(data.get("responseList")):
                        for i in data["responseList"]:
                            if i.get("name"):
                                i["api"] = api_id
                                response_serialize = ApiResponseDeserializer(
                                    data=i)
                                if response_serialize.is_valid():
                                    response_serialize.save(
                                        api=ApiInfo.objects.get(id=api_id))
                    record_dynamic(project=data["project_id"],
                                   _type="新增",
                                   operationObject="接口",
                                   user=user.pk,
                                   data="新增接口“%s”" % data["name"])
                    api_record = ApiOperationHistory(
                        api=ApiInfo.objects.get(id=api_id),
                        user=User.objects.get(id=user.pk),
                        description="新增接口“%s”" % data["name"])
                    api_record.save()
        except Exception as e:
            print('*' * 8)
            logging.exception(e)
            return False
    except ObjectDoesNotExist:
        return False
def add_swagger_api(data, user):
    """
    swagger接口写入数据库
    :param data:  json数据
    :param user:  用户model
    :return:
    """
    obj = Project.objects.filter(id=data["project_id"])
    if obj:
        try:
            with transaction.atomic():
                serialize = ApiInfoDeserializer(data=data)
                if serialize.is_valid():
                    serialize.save(project=obj)
                    api_id = serialize.data.get("id")
                    try:
                        if len(data["headDict"]):
                            for i in data["headDict"]:
                                try:
                                    if i["name"]:
                                        i["api"] = api_id
                                        head_serialize = ApiHeadDeserializer(
                                            data=i)
                                        if head_serialize.is_valid():
                                            head_serialize.save(
                                                api=ApiInfo.objects.get(
                                                    id=api_id))
                                except KeyError:
                                    pass
                    except KeyError:
                        pass
                    if data["requestParameterType"] == "form-data":
                        try:
                            if len(data["requestList"]):
                                for i in data["requestList"]:
                                    try:
                                        if i["name"]:
                                            i["api"] = api_id
                                            param_serialize = ApiParameterDeserializer(
                                                data=i)
                                            if param_serialize.is_valid():
                                                param_serialize.save(
                                                    api=ApiInfo.objects.get(
                                                        id=api_id))
                                    except KeyError:
                                        pass
                        except KeyError:
                            pass
                    else:
                        try:
                            if len(data["requestList"]):
                                ApiParameterRaw(
                                    api=ApiInfo.objects.get(id=api_id),
                                    data=data["requestList"]).save()
                        except KeyError:
                            pass
                    try:
                        if len(data["responseList"]):
                            for i in data["responseList"]:
                                try:
                                    if i["name"]:
                                        i["api"] = api_id
                                        response_serialize = ApiResponseDeserializer(
                                            data=i)
                                        if response_serialize.is_valid():
                                            response_serialize.save(
                                                api=ApiInfo.objects.get(
                                                    id=api_id))
                                except KeyError:
                                    pass
                    except KeyError:
                        pass
                    record_dynamic(project=data["project_id"],
                                   _type="新增",
                                   operationObject="接口",
                                   user=user.pk,
                                   data="新增接口“%s”" % data["name"])
                    api_record = ApiOperationHistory(
                        apiInfo=ApiInfo.objects.get(id=api_id),
                        user=User.objects.get(id=user.pk),
                        description="新增接口\"%s\"" % data["name"])
                    api_record.save()
        except Exception as e:
            logging.exception("error")
            logging.error(e)
Esempio n. 8
0
 def updateApi(data):
     with transaction.atomic():
         try:
             serialize = ApiInfoDeserializer(data=data)
             if serialize.is_valid():
                 try:
                     data["userUpdate"] = User.objects.get(
                         id=data["userUpdate"])
                     obi = ApiInfo.objects.get(id=data["id"])
                     serialize.update(instance=obi, validated_data=data)
                 except KeyError:
                     serialize.update(instance=obi, validated_data=data)
                 header = Q()
                 if "headDict" in data and len(data.get("headDict")):
                     for i in data["headDict"]:
                         if i.get("api") and i.get("id"):
                             header = header | Q(id=i["id"])
                             if i["name"]:
                                 head_serialize = ApiHeadDeserializer(
                                     data=i)
                                 if head_serialize.is_valid():
                                     i["api"] = ApiInfo.objects.get(
                                         id=i["api"])
                                     head_serialize.update(
                                         instance=ApiHead.objects.get(
                                             id=i["id"]),
                                         validated_data=i)
                         else:
                             if i.get("name"):
                                 i["api"] = data['id']
                                 head_serialize = ApiHeadDeserializer(
                                     data=i)
                                 if head_serialize.is_valid():
                                     head_serialize.save(
                                         api=ApiInfo.objects.get(
                                             id=data["id"]))
                                     header = header | Q(
                                         id=head_serialize.data.get("id"))
                 ApiHead.objects.exclude(header).filter(
                     api=data["id"]).delete()
                 api_param = Q()
                 api_param_raw = Q()
                 if "requestList" in data and len(data.get("requestList")):
                     if data["requestParameterType"] in (
                             "application/x-www-form-urlencoded",
                             "application/json", "text/plain"):
                         ApiParameterRaw.objects.filter(
                             api=data["id"]).delete()
                         for i in data["requestList"]:
                             if i.get("api") and i.get("id"):
                                 api_param = api_param | Q(id=i["id"])
                                 if i["name"]:
                                     param_serialize = ApiParameterDeserializer(
                                         data=i)
                                     if param_serialize.is_valid():
                                         i["api"] = ApiInfo.objects.get(
                                             id=i["api"])
                                         param_serialize.update(
                                             instance=ApiParameter.objects.
                                             get(id=i["id"]),
                                             validated_data=i)
                             else:
                                 if i.get("name"):
                                     i["api"] = data['id']
                                     param_serialize = ApiParameterDeserializer(
                                         data=i)
                                     if param_serialize.is_valid():
                                         param_serialize.save(
                                             api=ApiInfo.objects.get(
                                                 id=data["id"]))
                                         api_param = api_param | Q(
                                             id=param_serialize.data.get(
                                                 "id"))
                     else:
                         try:
                             obj = ApiParameterRaw.objects.get(
                                 api=data["id"])
                             obj.data = data["requestList"]
                             obj.save()
                         except ObjectDoesNotExist:
                             obj = ApiParameterRaw(
                                 api=ApiInfo.objects.get(id=data['id']),
                                 data=data["requestList"])
                             obj.save()
                         api_param_raw = api_param_raw | Q(id=obj.id)
                 ApiParameter.objects.exclude(api_param).filter(
                     api=data["id"]).delete()
                 ApiParameterRaw.objects.exclude(api_param_raw).filter(
                     api=data["id"]).delete()
                 api_response = Q()
                 if "responseList" in data and len(
                         data.get("responseList")):
                     for i in data["responseList"]:
                         if i.get("api") and i.get("id"):
                             api_response = api_response | Q(id=i["id"])
                             if i["name"]:
                                 response_serialize = ApiResponseDeserializer(
                                     data=i)
                                 if response_serialize.is_valid():
                                     i["api"] = ApiInfo.objects.get(
                                         id=i["api"])
                                     response_serialize.update(
                                         instance=ApiResponse.objects.get(
                                             id=i["id"]),
                                         validated_data=i)
                         else:
                             if i.get("name"):
                                 i["api"] = data['id']
                                 response_serialize = ApiResponseDeserializer(
                                     data=i)
                                 if response_serialize.is_valid():
                                     response_serialize.save(
                                         api=ApiInfo.objects.get(
                                             id=data["id"]))
                                     api_response = api_response | Q(
                                         id=response_serialize.data.get(
                                             "id"))
                 ApiResponse.objects.exclude(api_response).filter(
                     api=data["id"]).delete()
                 return data
             else:
                 print("更新接口[%s]出现异常: %s" % (data["name"], serialize.error))
                 return None
         except:
             logging.error(traceback.format_exc())