def post(self, request):
     """
     删除接口请求历史
     :param request:
     :return:
     """
     data = JSONParser().parse(request)
     result = self.parameter_check(data)
     if result:
         return result
     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="该项目已禁用")
     try:
         obj = ApiInfo.objects.get(id=data["api_id"], project=data["project_id"])
     except ObjectDoesNotExist:
         return JsonResponse(code="999990", msg="接口不存在!")
     obm = APIRequestHistory.objects.filter(id=data["id"], api=data["api_id"])
     if obm:
         obm.delete()
         api_record = ApiOperationHistory(api=obj,
                                          user=User.objects.get(id=request.user.pk),
                                          description="删除请求历史记录")
         api_record.save()
         return JsonResponse(code="999999", msg="成功!")
     else:
         return JsonResponse(code="999988", msg="请求历史不存在!")
Beispiel #2
0
 def post(self, request):
     """
     新增接口
     :param request:
     :return:
     """
     data=request.data
     result = self.parameter_check(data)
     if result:
         return result
     data["userUpdate"] = request.user.pk
     data["params"]="{}" if not "params" in data or not data["params"] else data["params"]
     api_name = ApiInfo.objects.filter(name=data["name"], project=data["project_id"])
     if len(api_name):
         return JsonResponse(code="999997", msg="存在相同名称!")
     else:
         result=ApiService.addApi(data)
         if result:
             record_dynamic(project=data["project_id"],
                                _type="新增", operationObject="接口", user=request.user.pk,
                                data="新增接口“%s”" % data["name"])
             api_record = ApiOperationHistory(api=ApiInfo.objects.get(id=result["id"]),
                                              user=User.objects.get(id=request.user.pk),
                                              description="新增接口“%s”" % data["name"])
             api_record.save()
             return JsonResponse(code="999999", msg="执行成功!", data={"api_id": result["id"]})
         else:
             return JsonResponse(code="999996", msg="执行失败!")
Beispiel #3
0
 def post(self, request):
     """
     修改接口
     :param request:
     :return:
     """
     data=request.data
     result = self.parameter_check(data)
     if result:
         return result
     data["userUpdate"] = request.user.pk
     data["params"]="{}" if not "params" in data or not data["params"] else data["params"]
     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="存在相同名称!")
     # data["userUpdate"] = request.user
     result=ApiService.updateApi(data)
     if result:
         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="999996", msg="执行失败!")
def del_history(request):
    """
    删除请求历史
    project_id 项目ID
    api_id 接口ID
    history_id 请求历史ID
    :return:
    """
    project_id = request.POST.get("project_id")
    api_id = request.POST.get("api_id")
    history_id = request.POST.get("history_id")
    if not project_id.isdecimal() or not api_id.isdecimal(
    ) or not history_id.isdecimal():
        return JsonResponse(code_msg=GlobalStatusCode.parameter_wrong())
    obj = Project.objects.filter(id=project_id)
    if obj:
        obi = ApiInfo.objects.filter(id=api_id, project=project_id)
        if obi:
            obm = APIRequestHistory.objects.filter(id=history_id,
                                                   apiInfo=api_id)
            if obm:
                obm.delete()
                api_record = ApiOperationHistory(
                    apiInfo=ApiInfo.objects.get(id=api_id),
                    user=User.objects.get(id=request.user.pk),
                    description="删除请求历史记录")
                api_record.save()
                return JsonResponse(code_msg=GlobalStatusCode.success())
            else:
                return JsonResponse(
                    code_msg=GlobalStatusCode.history_not_exist())
        else:
            return JsonResponse(code_msg=GlobalStatusCode.api_not_exist())
    else:
        return JsonResponse(code_msg=GlobalStatusCode.project_not_exist())
 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="分组不存在!")
 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="分组不存在!")
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():
                oba = ApiInfo(
                    project=Project.objects.get(id=data["project_id"]),
                    name=data["name"],
                    httpType=data["httpType"],
                    status=data["status"],
                    requestType=data["requestType"],
                    apiAddress=data["address"],
                    requestParameterType=data["requestParameterType"],
                    mockCode=data["mockStatus"],
                    data=data["code"],
                    userUpdate=User.objects.get(id=user.pk),
                    description=data["desc"])
                oba.save()
                if len(data["headDict"]):
                    for i in data["headDict"]:
                        try:
                            if i["name"]:
                                ApiHead(api=ApiInfo.objects.get(id=oba.pk),
                                        name=i["name"],
                                        value=i["value"]).save()
                        except KeyError:
                            logging.exception("Error")
                if data["requestParameterType"] == "form-data":
                    if len(data["requestList"]):
                        for i in data["requestList"]:
                            try:
                                # i = i.replace("true", "True").replace("false", "False")
                                if i["name"]:
                                    ApiParameter(
                                        api=ApiInfo.objects.get(id=oba.pk),
                                        name=i["name"],
                                        value=i["value"],
                                        required=i["required"],
                                        _type=i["_type"],
                                        restrict=i["restrict"],
                                        description=i["description"]).save()
                            except KeyError:
                                logging.exception("Error")
                else:
                    if len(data["requestList"]):
                        _data = data["requestList"].replace("\'", "\"")
                        ApiParameterRaw(api=ApiInfo.objects.get(id=oba.pk),
                                        data=_data).save()
                if len(data["responseList"]):
                    for i in data["responseList"]:
                        try:
                            # i = i.replace("true", "True").replace("false", "False")
                            if i["name"]:
                                ApiResponse(
                                    api=ApiInfo.objects.get(id=oba.pk),
                                    name=i["name"],
                                    value=i["value"],
                                    required=i["required"],
                                    _type=i["_type"],
                                    description=i["description"]).save()
                        except KeyError:
                            logging.exception("Error")
                record_dynamic(data["project_id"], "新增", "接口",
                               "新增接口“%s”" % data["name"])
                api_record = ApiOperationHistory(
                    apiInfo=ApiInfo.objects.get(id=oba.pk),
                    user=User.objects.get(id=user.pk),
                    description="新增接口\"%s\"" % data["name"])
                api_record.save()
        except Exception as e:
            logging.exception("error")
            logging.error(e)
Beispiel #8
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 update_api(request):
    """
    修改接口信息
    project_id 项目ID
    api_id 接口ID
    first_group_id 一级分组ID
    second_group_id 二级分组ID
    name 接口名称
    httpType  HTTP/HTTPS
    requestType 请求方式
    address  请求地址
    headDict 头文件
    requestParameterType 参数请求格式
    requestList 请求参数列表
    responseList 返回参数列表
    mockStatus  mockhttp状态
    code mock代码
    description 描述
    :return:
    """
    data = json.loads(request.body)
    if not data["project_id"] or not data["first_group_id"] or not data["name"] or not data["httpType"] or not \
            data["requestType"] or not data["address"] or not data["requestParameterType"] or not data["status"] or \
            not data["api_id"]:
        return JsonResponse(code_msg=GlobalStatusCode.parameter_wrong())
    if not isinstance(data["project_id"], int) or not isinstance(data["first_group_id"], int) or \
            not isinstance(data["api_id"], int):
        return JsonResponse(code_msg=GlobalStatusCode.parameter_wrong())
    if data["status"] not in ["True", "False"]:
        return JsonResponse(code_msg=GlobalStatusCode.parameter_wrong())
    if not isinstance(data["project_id"], int) or not isinstance(
            data["first_group_id"], int):
        return JsonResponse(code_msg=GlobalStatusCode.parameter_wrong())
    if data["httpType"] not in ["HTTP", "HTTPS"]:
        return JsonResponse(code_msg=GlobalStatusCode.parameter_wrong())
    if data["requestType"] not in ["POST", "GET", "PUT", "DELETE"]:
        return JsonResponse(code_msg=GlobalStatusCode.parameter_wrong())
    if data["requestParameterType"] not in ["form-data", "raw", "Restful"]:
        return JsonResponse(code_msg=GlobalStatusCode.parameter_wrong())
    obj = Project.objects.filter(id=data["project_id"])
    if obj:
        obm = ApiInfo.objects.filter(id=data["api_id"],
                                     project=data["project_id"])
        if obm:
            obi = ApiInfo.objects.filter(
                name=data["name"],
                project=data["project_id"]).exclude(id=data["api_id"])
            if len(obi) == 0:
                try:
                    with transaction.atomic():
                        first_group = ApiGroupLevelFirst.objects.filter(
                            id=data["first_group_id"],
                            project=data["project_id"])
                        if len(first_group) == 0:
                            return JsonResponse(
                                code_msg=GlobalStatusCode.group_not_exist())
                        if data["first_group_id"] and data["second_group_id"]:
                            if not isinstance(data["second_group_id"], int):
                                return JsonResponse(code_msg=GlobalStatusCode.
                                                    parameter_wrong())
                            second_group = ApiGroupLevelSecond.objects.filter(
                                id=data["second_group_id"],
                                apiGroupLevelFirst=data["first_group_id"])
                            if len(second_group) == 0:
                                return JsonResponse(code_msg=GlobalStatusCode.
                                                    group_not_exist())
                            try:
                                obm.update(
                                    project=Project.objects.get(
                                        id=data["project_id"]),
                                    apiGroupLevelFirst=ApiGroupLevelFirst.
                                    objects.get(id=data["first_group_id"]),
                                    apiGroupLevelSecond=ApiGroupLevelSecond.
                                    objects.get(id=data["second_group_id"]),
                                    name=data["name"],
                                    httpType=data["httpType"],
                                    requestType=data["requestType"],
                                    apiAddress=data["address"],
                                    requestParameterType=data[
                                        "requestParameterType"],
                                    mockCode=data["mockStatus"],
                                    data=data["code"],
                                    status=data["status"],
                                    userUpdate=User.objects.get(
                                        id=request.user.pk),
                                    description=data["description"])
                            except KeyError:
                                return JsonResponse(code_msg=GlobalStatusCode.
                                                    parameter_wrong())
                        else:
                            return JsonResponse(
                                code_msg=GlobalStatusCode.parameter_wrong())
                        if len(data["headDict"]):
                            _list = []
                            for j in data["headDict"]:
                                try:
                                    _list.append(j["id"])
                                except KeyError:
                                    pass
                            parameter = ApiHead.objects.filter(
                                api=data["api_id"])
                            for n in parameter:
                                if n.pk not in _list:
                                    n.delete()
                            for i in data["headDict"]:
                                if i["name"]:
                                    try:
                                        ApiHead.objects.filter(id=i["id"], api=data["api_id"]).\
                                            update(name=i["name"], value=i["value"])
                                    except KeyError:
                                        ApiHead(api=ApiInfo.objects.get(
                                            id=data["api_id"]),
                                                name=i["name"],
                                                value=i["value"]).save()
                        if data["requestParameterType"] == "form-data":
                            ApiParameterRaw.objects.filter(
                                api=data["api_id"]).delete()
                            if len(data["requestList"]):
                                _list = []
                                for j in data["requestList"]:
                                    try:
                                        _list.append(j["id"])
                                    except KeyError:
                                        pass
                                parameter = ApiParameter.objects.filter(
                                    api=data["api_id"])
                                for n in parameter:
                                    if n.pk not in _list:
                                        n.delete()
                                for i in data["requestList"]:
                                    try:
                                        if i["name"]:
                                            try:
                                                ApiParameter.objects.filter(id=i["id"], api=data["api_id"]).\
                                                    update(name=i["name"], value=i["value"], required=i["required"],
                                                           restrict=i["restrict"], _type=i["_type"],
                                                           description=i["description"])
                                            except KeyError:
                                                ApiParameter(
                                                    api=ApiInfo.objects.get(
                                                        id=data["api_id"]),
                                                    name=i["name"],
                                                    value=i["value"],
                                                    required=i["required"],
                                                    _type=i["_type"],
                                                    description=i[
                                                        "description"]).save()
                                    except KeyError:
                                        logging.exception("Error")
                                        return JsonResponse(
                                            code_msg=GlobalStatusCode.
                                            parameter_wrong())

                        else:
                            ApiParameterRaw.objects.filter(
                                api=data["api_id"]).delete()
                            ApiParameter.objects.filter(
                                api=data["api_id"]).delete()
                            if data["requestList"]:
                                ApiParameterRaw(
                                    api=ApiInfo.objects.get(id=data["api_id"]),
                                    data=data["requestList"]).save()

                        if len(data["responseList"]):
                            _list = []
                            for j in data["responseList"]:
                                try:
                                    _list.append(j["id"])
                                except KeyError:
                                    pass
                            parameter = ApiResponse.objects.filter(
                                api=data["api_id"])
                            for n in parameter:
                                if n.pk not in _list:
                                    n.delete()
                            for i in data["responseList"]:
                                if i["name"]:
                                    try:
                                        ApiResponse.objects.filter(id=i["id"], api=data["api_id"]).\
                                            update(name=i["name"], value=i["value"], required=i["required"],
                                                   _type=i["_type"],
                                                   description=i["description"])
                                    except KeyError:
                                        ApiResponse(
                                            api=ApiInfo.objects.get(
                                                id=data["api_id"]),
                                            name=i["name"],
                                            value=i["value"],
                                            required=i["required"],
                                            _type=i["_type"],
                                            description=i["description"]).save(
                                            )
                            record_dynamic(data["project_id"], "修改", "接口",
                                           "修改接口“%s”" % data["name"])
                        api_record = ApiOperationHistory(
                            apiInfo=ApiInfo.objects.get(id=data["api_id"]),
                            user=User.objects.get(id=request.user.pk),
                            description="修改接口\"%s\"" % data["name"])
                        api_record.save()
                        return JsonResponse(
                            code_msg=GlobalStatusCode.success())
                except Exception as e:
                    logging.exception("ERROR")
                    logging.error(e)
                    return JsonResponse(code_msg=GlobalStatusCode.fail())
            else:
                return JsonResponse(code_msg=GlobalStatusCode.api_is_exist())
        else:
            return JsonResponse(code_msg=GlobalStatusCode.api_not_exist())
    else:
        return JsonResponse(code_msg=GlobalStatusCode.project_not_exist())
Beispiel #10
0
def add_api(request):
    """
    新增接口信息
    project_id 项目ID
    first_group_id 一级分组ID
    second_group_id 二级分组ID
    name 接口名称
    httpType  HTTP/HTTPS
    requestType 请求方式
    address  请求地址
    headDict 头文件
    requestParameterType 参数请求格式
    requestList 请求参数列表
    responseList 返回参数列表
    mockStatus  mockhttp状态
    code mock代码
    description 描述
    :return:
    """
    data = json.loads(request.body)
    if not data["project_id"] or not data["first_group_id"] or not data["name"] or not data["httpType"] or not \
            data["requestType"] or not data["address"] or not data["requestParameterType"] or not data["status"]:
        return JsonResponse(code_msg=GlobalStatusCode.parameter_wrong())
    if data["status"] not in ["True", "False"]:
        return JsonResponse(code_msg=GlobalStatusCode.parameter_wrong())
    if not isinstance(data["project_id"], int) or not isinstance(
            data["first_group_id"], int):
        return JsonResponse(code_msg=GlobalStatusCode.parameter_wrong())
    if data["httpType"] not in ["HTTP", "HTTPS"]:
        return JsonResponse(code_msg=GlobalStatusCode.parameter_wrong())
    if data["requestType"] not in ["POST", "GET", "PUT", "DELETE"]:
        return JsonResponse(code_msg=GlobalStatusCode.parameter_wrong())
    if data["requestParameterType"] not in ["form-data", "raw", "Restful"]:
        return JsonResponse(code_msg=GlobalStatusCode.parameter_wrong())
    obj = Project.objects.filter(id=data["project_id"])
    if obj:
        obi = ApiInfo.objects.filter(name=data["name"],
                                     project=data["project_id"])
        if obi:
            return JsonResponse(code_msg=GlobalStatusCode.name_repetition())
        else:
            try:
                with transaction.atomic():
                    first_group = ApiGroupLevelFirst.objects.filter(
                        id=data["first_group_id"], project=data["project_id"])
                    if len(first_group) == 0:
                        return JsonResponse(
                            code_msg=GlobalStatusCode.group_not_exist())
                    if data["first_group_id"] and data["second_group_id"]:
                        if not isinstance(data["second_group_id"], int):
                            return JsonResponse(
                                code_msg=GlobalStatusCode.parameter_wrong())
                        second_group = ApiGroupLevelSecond.objects.filter(
                            id=data["second_group_id"],
                            apiGroupLevelFirst=data["first_group_id"])
                        if len(second_group) == 0:
                            return JsonResponse(
                                code_msg=GlobalStatusCode.group_not_exist())
                        try:
                            oba = ApiInfo(
                                project=Project.objects.get(
                                    id=data["project_id"]),
                                apiGroupLevelFirst=ApiGroupLevelFirst.objects.
                                get(id=data["first_group_id"]),
                                apiGroupLevelSecond=ApiGroupLevelSecond.
                                objects.get(id=data["second_group_id"]),
                                name=data["name"],
                                httpType=data["httpType"],
                                status=data["status"],
                                requestType=data["requestType"],
                                apiAddress=data["address"],
                                requestParameterType=data[
                                    "requestParameterType"],
                                mockCode=data["mockStatus"],
                                data=data["code"],
                                userUpdate=User.objects.get(
                                    id=request.user.pk),
                                description=data["desc"])
                        except KeyError:
                            return JsonResponse(
                                code_msg=GlobalStatusCode.parameter_wrong())
                    else:
                        return JsonResponse(
                            code_msg=GlobalStatusCode.parameter_wrong())
                    oba.save()
                    if len(data["headDict"]):
                        for i in data["headDict"]:
                            try:
                                if i["name"]:
                                    ApiHead(api=ApiInfo.objects.get(id=oba.pk),
                                            name=i["name"],
                                            value=i["value"]).save()
                            except KeyError:
                                logging.exception("Error")
                                return JsonResponse(GlobalStatusCode.fail())
                    if data["requestParameterType"] == "form-data":
                        if len(data["requestList"]):
                            for i in data["requestList"]:
                                try:
                                    # i = i.replace("true", "True").replace("false", "False")
                                    if i["name"]:
                                        ApiParameter(
                                            api=ApiInfo.objects.get(id=oba.pk),
                                            name=i["name"],
                                            value=i["value"],
                                            required=i["required"],
                                            _type=i["_type"],
                                            restrict=i["restrict"],
                                            description=i["description"]).save(
                                            )
                                except KeyError:
                                    logging.exception("Error")
                                    return JsonResponse(
                                        code_msg=GlobalStatusCode.fail())
                    else:
                        if len(data["requestList"]):
                            ApiParameterRaw(api=ApiInfo.objects.get(id=oba.pk),
                                            data=data["requestList"]).save()
                    if len(data["responseList"]):
                        for i in data["responseList"]:
                            try:
                                # i = i.replace("true", "True").replace("false", "False")
                                if i["name"]:
                                    ApiResponse(
                                        api=ApiInfo.objects.get(id=oba.pk),
                                        name=i["name"],
                                        value=i["value"],
                                        required=i["required"],
                                        _type=i["_type"],
                                        description=i["description"]).save()
                            except KeyError:
                                logging.exception("Error")
                                return JsonResponse(
                                    code_msg=GlobalStatusCode.fail())
                    record_dynamic(data["project_id"], "新增", "接口",
                                   "新增接口“%s”" % data["name"])
                    api_record = ApiOperationHistory(
                        apiInfo=ApiInfo.objects.get(id=oba.pk),
                        user=User.objects.get(id=request.user.pk),
                        description="新增接口\"%s\"" % data["name"])
                    api_record.save()
                    return JsonResponse(data={"api_id": oba.pk},
                                        code_msg=GlobalStatusCode.success())
            except Exception as e:
                logging.exception("error")
                logging.error(e)
                return JsonResponse(code_msg=GlobalStatusCode.fail())
    else:
        return JsonResponse(code_msg=GlobalStatusCode.project_not_exist())
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)
Beispiel #12
0
def update_api(request):
    """
    修改接口信息
    project_id 项目ID
    api_id 接口ID
    first_group_id 一级分组ID
    second_group_id 二级分组ID
    name 接口名称
    httpType  HTTP/HTTPS
    requestType 请求方式
    address  请求地址
    headDict 头文件
    requestParameterType 参数请求格式
    requestList 请求参数列表
    responseList 返回参数列表
    mockStatus  mockhttp状态
    code mock代码
    description 描述
    :return:
    """
    project_id = request.POST.get('project_id')
    api_id = request.POST.get('api_id')
    first_group_id = request.POST.get('first_group_id')
    second_group_id = request.POST.get('second_group_id')
    if not project_id.isdecimal() or not api_id.isdecimal(
    ) or not first_group_id.isdecimal():
        return JsonResponse(code_msg=GlobalStatusCode.parameter_wrong())
    name = request.POST.get('name')
    http_type = request.POST.get('httpType')
    request_type = request.POST.get('requestType')
    address = request.POST.get('address')
    head_dict = request.POST.get('headDict')
    request_parameter_type = request.POST.get('requestParameterType')
    request_list = request.POST.get('requestList')
    response_list = request.POST.get('responseList')
    mock_status = request.POST.get('mockStatus')
    code = request.POST.get('code')
    description = request.POST.get('description')
    status = request.POST.get('status')
    if status not in ['True', 'False']:
        return JsonResponse(code_msg=GlobalStatusCode.parameter_wrong())
    if http_type not in ['HTTP', 'HTTPS']:
        return JsonResponse(code_msg=GlobalStatusCode.parameter_wrong())
    if request_type not in ['POST', 'GET', 'PUT', 'DELETE']:
        return JsonResponse(code_msg=GlobalStatusCode.parameter_wrong())
    if request_parameter_type not in ['form-data', 'raw', 'Restful']:
        return JsonResponse(code_msg=GlobalStatusCode.parameter_wrong())
    obj = Project.objects.filter(id=project_id)
    if obj:
        obm = ApiInfo.objects.filter(id=api_id, project=project_id)
        if obm:
            obi = ApiInfo.objects.filter(name=name,
                                         project=project_id).exclude(id=api_id)
            if len(obi) == 0:
                try:
                    with transaction.atomic():
                        first_group = ApiGroupLevelFirst.objects.filter(
                            id=first_group_id, project=project_id)
                        if len(first_group) == 0:
                            return JsonResponse(
                                code_msg=GlobalStatusCode.group_not_exist())
                        if first_group_id and second_group_id:
                            if not second_group_id.isdecimal():
                                return JsonResponse(code_msg=GlobalStatusCode.
                                                    parameter_wrong())
                            second_group = ApiGroupLevelSecond.objects.filter(
                                id=second_group_id,
                                apiGroupLevelFirst=first_group_id)
                            if len(second_group) == 0:
                                return JsonResponse(code_msg=GlobalStatusCode.
                                                    group_not_exist())
                            obm.update(
                                project=Project.objects.get(id=project_id),
                                apiGroupLevelFirst=ApiGroupLevelFirst.objects.
                                get(id=first_group_id),
                                apiGroupLevelSecond=ApiGroupLevelSecond.
                                objects.get(id=second_group_id),
                                name=name,
                                httpType=http_type,
                                requestType=request_type,
                                apiAddress=address,
                                requestParameterType=request_parameter_type,
                                mockCode=mock_status,
                                data=code,
                                userUpdate=User.objects.get(
                                    id=request.user.pk),
                                description=description)
                        else:
                            return JsonResponse(
                                code_msg=GlobalStatusCode.parameter_wrong())
                        if head_dict:
                            head = re.findall('{.*?}', head_dict)
                            _list = []
                            for j in head:
                                try:
                                    j = eval(j)
                                    try:
                                        _list.append(j["id"])
                                    except KeyError:
                                        pass
                                except:
                                    return JsonResponse(
                                        code_msg=GlobalStatusCode.fail())
                            parameter = ApiHead.objects.filter(api=api_id)
                            for n in parameter:
                                if n.pk not in _list:
                                    n.delete()
                            for i in head:
                                try:
                                    i = eval(i)
                                    if i['name']:
                                        try:
                                            ApiHead.objects.filter(id=i['id'], api=api_id).\
                                                update(name=i['name'], value=i['value'])
                                        except KeyError:
                                            ApiHead(api=ApiInfo.objects.get(
                                                id=api_id),
                                                    name=i['name'],
                                                    value=i['value']).save()
                                except Exception as e:
                                    logging.exception("Error")
                                    return JsonResponse(
                                        code_msg=GlobalStatusCode.fail())
                        if request_parameter_type == 'form-data':
                            ApiParameterRaw.objects.filter(api=api_id).delete()
                            if request_list:
                                request_list = re.findall(
                                    '{.*?}', request_list)
                                _list = []
                                for j in request_list:
                                    try:
                                        j = eval(
                                            j.replace("true", "True").replace(
                                                "false", "False"))
                                        try:
                                            _list.append(j["id"])
                                        except KeyError:
                                            pass
                                    except:
                                        return JsonResponse(
                                            code_msg=GlobalStatusCode.fail())
                                parameter = ApiParameter.objects.filter(
                                    api=api_id)
                                for n in parameter:
                                    if n.pk not in _list:
                                        n.delete()
                                for i in request_list:
                                    try:
                                        i = eval(
                                            i.replace("true", "True").replace(
                                                "false", "False"))
                                        if i['name']:
                                            try:
                                                ApiParameter.objects.filter(id=i['id'], api=api_id).\
                                                    update(name=i['name'], value=i['value'], required=i['required'],
                                                           restrict=i['restrict'], _type=i['_type'],
                                                           description=i['description'])
                                            except KeyError:
                                                ApiParameter(
                                                    api=ApiInfo.objects.get(
                                                        id=api_id),
                                                    name=i['name'],
                                                    value=i['value'],
                                                    required=i['required'],
                                                    _type=i['_type'],
                                                    description=i[
                                                        'description']).save()
                                    except Exception as e:
                                        logging.exception("Error")
                                        return JsonResponse(
                                            code_msg=GlobalStatusCode.fail())

                        else:
                            ApiParameterRaw.objects.filter(api=api_id).delete()
                            ApiParameter.objects.filter(api=api_id).delete()
                            if request_list:
                                ApiParameterRaw(
                                    api=ApiInfo.objects.get(id=api_id),
                                    data=request_list).save()

                        if response_list:
                            response_list = re.findall('{.*?}', response_list)
                            _list = []
                            for j in response_list:
                                try:
                                    j = eval(
                                        j.replace("true", "True").replace(
                                            "false", "False"))
                                    try:
                                        _list.append(j["id"])
                                    except KeyError:
                                        pass
                                except:
                                    return JsonResponse(
                                        code_msg=GlobalStatusCode.fail())
                            parameter = ApiResponse.objects.filter(api=api_id)
                            for n in parameter:
                                if n.pk not in _list:
                                    n.delete()
                            for i in response_list:
                                try:
                                    i = eval(
                                        i.replace("true", "True").replace(
                                            "false", "False"))
                                    if i['name']:
                                        try:
                                            ApiResponse.objects.filter(id=i['id'], api=api_id).\
                                                update(name=i['name'], value=i['value'], required=i['required'],
                                                       _type=i['_type'],
                                                       description=i['description'])
                                        except KeyError:
                                            ApiResponse(
                                                api=ApiInfo.objects.get(
                                                    id=api_id),
                                                name=i['name'],
                                                value=i['value'],
                                                required=i['required'],
                                                _type=i['_type'],
                                                description=i['description']
                                            ).save()
                                except Exception as e:
                                    logging.exception("error")
                                    return JsonResponse(
                                        code_msg=GlobalStatusCode.fail())
                            record_dynamic(project_id, '修改', '接口',
                                           '修改接口“%s”' % name)
                        api_record = ApiOperationHistory(
                            apiInfo=ApiInfo.objects.get(id=api_id),
                            user=User.objects.get(id=request.user.pk),
                            description='修改接口"%s"' % name)
                        api_record.save()
                        return JsonResponse(
                            code_msg=GlobalStatusCode.success())
                except Exception as e:
                    logging.exception('ERROR')
                    logging.error(e)
                    return JsonResponse(code_msg=GlobalStatusCode.fail())
            else:
                return JsonResponse(code_msg=GlobalStatusCode.api_is_exist())
        else:
            return JsonResponse(code_msg=GlobalStatusCode.api_not_exist())
    else:
        return JsonResponse(code_msg=GlobalStatusCode.project_not_exist())