# -*- coding: utf-8 -*-
# @Time    : 2021/4/1 10:50
# @Author  : wangyinghao
# @FileName: api_test_case_view.py
# @Software: PyCharm
from django.views.generic import View
import json
import re
from django.forms import model_to_dict
from automated_main.utils.http_format import response_success, response_failed
from automated_main.exception.my_exception import MyException
from automated_main.models.api_automation.api_test_case import ApiTestCase, ApiParameterExtraction, ApiParameterData
from automated_main.form.api_test_case import ApiTestCaseForm
from automated_main.models.api_automation.api_environment import APIEnvironment
from automated_main.models.api_automation.api_project import APIProject
from automated_main.models.api_automation.api_module import APIModule
from automated_main.models.api_automation.api_database import APIDatabase
from automated_main.utils.handle_db import HandleDB
from automated_main.utils.api_utils import RegularMatch, InterfaceRequest, ExtractParameters
from AutomatedTestPlatform import settings
from automated_main.utils.api_test_case_excel import HandleExcel
from django.http import FileResponse
import time
import random
import os
import logging

logger = logging.getLogger('django')


class ApiTestCaseView(View):

    def delete(self, request, api_test_case_id, *args, **kwargs):
        """
         代表删除API测试用例
        :param request:
        :param api_test_case_id:
        :param args:
        :param kwargs:
        :return:
        """

        ApiTestCase.objects.delete()
        return response_success("删除API测试用例成功")

    def put(self, request, *args, **kwargs):
        """
        创建API测试用例
        :param request:
        :param args:
        :param kwargs:
        :return:
        """
        body = request.body
        if not body:
            return response_success()
        data = json.loads(body)
        form = ApiTestCaseForm(data)

        if form.is_valid():
            api_test_case = ApiTestCase.objects
            api_test_case_id = api_test_case.id

            for api_parameter_extraction in data['api_parameter_extraction']:

                if api_parameter_extraction['api_key_variable'] == "":
                    pass

                elif api_parameter_extraction['api_key_variable'] != "":
                    if ApiParameterExtraction.objects.filter(
                            api_key_variable=api_parameter_extraction['api_key_variable']).count() > 0:
                        api_test_case.delete()
                        return response_failed("30000", "变量名称重复,请重新填写")
                    else:
                        ApiParameterExtraction.objects.create(api_test_case_id=api_test_case_id,
                                                              api_variable_results=api_parameter_extraction[
                                                                  'api_variable_results'],
                                                              api_value_variable=api_parameter_extraction[
                                                                  'api_value_variable'],
                                                              api_key_variable=api_parameter_extraction[
                                                                  'api_key_variable'])
            for api_parameter in data['api_parameter']:
                ApiParameterData.objects.create(api_test_case_id=api_test_case_id,
                                                api_parameter_name=api_parameter['api_parameter_name'],
                                                api_must_parameter=api_parameter['api_must_parameter'],
                                                api_parameter_value=api_parameter['api_parameter_value'],
                                                api_field_describe=api_parameter['api_field_describe'])

            return response_success("创建API测试用例成功")

        else:

            raise MyException()

    def post(self, request, api_test_case_id, *args, **kwargs):
        """
        编辑API测试用例
        :param request:
        :param args:
        :param api_test_case_id:
        :param kwargs:
        :return:
        """

        api_test_case = ApiTestCase.objects.filter(id=api_test_case_id).first()
        if api_test_case is None:
            return response_success()
        body = request.body
        if not body:
            return response_success()

        data = json.loads(body)
        form = ApiTestCaseForm(data)
        if form.is_valid():
            if ApiParameterExtraction.objects.filter(api_test_case_id=api_test_case_id).count() > 0:
                ApiParameterExtraction.objects.delete()

                for api_parameter_extraction in data['api_parameter_extraction']:
                    if api_parameter_extraction['api_key_variable'] == "":
                        pass
                    elif ApiParameterExtraction.objects.filter(
                            api_key_variable=api_parameter_extraction['api_key_variable']).count() > 0:
                        return response_failed("30000", "变量名称重复,请重新填写")
                    else:
                        ApiParameterExtraction.objects.create(api_test_case_id=api_test_case_id,
                                                              api_variable_results=api_parameter_extraction[
                                                                  'api_variable_results'],
                                                              api_value_variable=api_parameter_extraction[
                                                                  'api_value_variable'],
                                                              api_key_variable=api_parameter_extraction[
                                                                  'api_key_variable'])

            else:
                logger.info("自定义变量表中 无 该 case_id")

                for api_parameter_extraction in data['api_parameter_extraction']:
                    if api_parameter_extraction['api_key_variable'] == "":
                        logger.info("api_key_variable是空")
                        pass

                    elif api_parameter_extraction['api_key_variable'] != "":
                        if ApiParameterExtraction.objects.filter(
                                api_key_variable=api_parameter_extraction['api_key_variable']).count() > 0:
                            return response_failed("30000", "变量名称重复,请重新填写")
                        else:
                            ApiParameterExtraction.objects.create(api_test_case_id=api_test_case_id,
                                                                  api_variable_results=api_parameter_extraction[
                                                                      'api_variable_results'],
                                                                  api_value_variable=api_parameter_extraction[
                                                                      'api_value_variable'],
                                                                  api_key_variable=api_parameter_extraction[
                                                                      'api_key_variable'])
            if ApiParameterData.objects.filter(api_test_case_id=api_test_case_id).count() > 0:
                ApiParameterData.objects.delete()
                for api_parameter in data['api_parameter']:
                    ApiParameterData.objects.create(api_test_case_id=api_test_case_id,
                                                    api_parameter_name=api_parameter['api_parameter_name'],
                                                    api_must_parameter=api_parameter['api_must_parameter'],
                                                    api_parameter_value=api_parameter['api_parameter_value'],
                                                    api_field_describe=api_parameter['api_field_describe'])
            else:
                for api_parameter in data['api_parameter']:
                    ApiParameterData.objects.create(api_test_case_id=api_test_case_id,
                                                    api_parameter_name=api_parameter['api_parameter_name'],
                                                    api_must_parameter=api_parameter['api_must_parameter'],
                                                    api_parameter_value=api_parameter['api_parameter_value'],
                                                    api_field_describe=api_parameter['api_field_describe'])

            ApiTestCase.objects.filter(id=api_test_case_id).update(**form.cleaned_data)

            return response_success("修改API测试用例成功")
        else:
            raise MyException()

    def get(self, request, api_test_case_id, *args, **kwargs):
        """
        获取单独API测试用例
        :param request:
        :param args:
        :param api_test_case_id:
        :param kwargs:
        :return:
        """

        api_test_case = ApiTestCase.objects.filter(id=api_test_case_id).first()
        api_parameter_extractions = ApiParameterExtraction.objects.filter(api_test_case_id=api_test_case_id)
        api_parameter_extraction_list = []

        api_parameter_data_list = []
        api_parameter_data = ApiParameterData.objects.filter(api_test_case_id=api_test_case_id)
        if api_parameter_data.count() > 0:
            for api_parameter in api_parameter_data:
                api_parameter_dict = {
                    "api_must_parameter": api_parameter.api_must_parameter,
                    "api_parameter_name": api_parameter.api_parameter_name,
                    "api_parameter_value": api_parameter.api_parameter_value,
                    "api_field_describe": api_parameter.api_field_describe
                }
                api_parameter_data_list.append(api_parameter_dict)

        if api_parameter_extractions.count() > 0:
            for api_parameter_extraction in api_parameter_extractions:
                api_parameter_extraction_dict = {
                    "api_variable_results": api_parameter_extraction.api_variable_results,
                    "api_value_variable": api_parameter_extraction.api_value_variable,
                    "api_key_variable": api_parameter_extraction.api_key_variable

                }
                api_parameter_extraction_list.append(api_parameter_extraction_dict)

        else:
            api_parameter_extraction_dict = {

                "api_variable_results": "",
                "api_value_variable": "",
                "api_key_variable": ""

            }
            api_parameter_extraction_list.append(api_parameter_extraction_dict)

        if api_test_case is None:
            return response_success()
        else:
            api_test_case_dict = model_to_dict(api_test_case)
            api_test_case_dict['api_parameter_extraction'] = api_parameter_extraction_list
            api_test_case_dict['api_parameter'] = api_parameter_data_list

            return response_success(api_test_case_dict)


class ApiTestCaseDeBugView(View):

    def post(self, request, *args, **kwargs):
        """
        API测试用例调试
        :param request:
        :param args:
        :param kwargs:
        :return:
        """
        data_payload = ''
        api_result = ''
        body = request.body

        if not body:
            return response_success()

        data = json.loads(body)
        # noinspection PyBroadException
        try:
            api_environment = APIEnvironment.objects.get(id=data['api_environment_id'])
        except Exception:
            return response_failed("30000", "请选择域名")

        # 请求地址
        api_url = api_environment.api_title + data['api_url']

        api_url = RegularMatch(api_url, data['api_environment_id'])
        if api_url[0] == "该变量数据库未找到":
            return response_failed("4000", str(api_url[0] + api_url[1]))

        api_headers = RegularMatch(data['api_headers'], data['api_environment_id'])
        if api_headers[0] == "该变量数据库未找到":
            return response_failed("4000", str(api_headers[0] + api_headers[1]))

        json_header = api_headers.replace("\'", "\"")
        if data['api_headers'] == '':
            header = data['api_headers']
        else:
            try:
                header = json.loads(json_header)
            except json.decoder.JSONDecodeError:
                return response_failed("30000", "header类型错误" + json_header)
        logger.info(json_header)

        # Params参数
        api_parameter = {}
        for api_parameters in data['api_parameter']:
            if api_parameters['api_must_parameter'] == "true":
                api_parameter.update({api_parameters['api_parameter_name']: api_parameters['api_parameter_value']})
            else:
                pass

        api_parameter_data = RegularMatch(str(api_parameter), data['api_environment_id'])
        if api_parameter_data[0] == "该变量数据库未找到":
            return response_failed("4000", str(api_parameter_data[0] + api_parameter_data[1]))

        data_parameter = api_parameter_data.replace("\'", "\"")
        if data_parameter == '':
            data_payload = api_parameter_data
            logger.info(data_payload)
        else:
            try:
                data_payload = json.loads(data_parameter)
                logger.info(data_payload)
            except json.decoder.JSONDecodeError:
                return response_failed("30000", "参数类型错误" + data_payload)

        api_parameter_body = RegularMatch(data['api_parameter_body'], data['api_environment_id'])
        if api_parameter_body[0] == "该变量数据库未找到":
            return response_failed("4000", str(api_parameter_body[0] + api_parameter_body[1]))

        json_par = api_parameter_body.replace("\'", "\"")
        if api_parameter_body == '':
            payload = api_parameter_body
            logger.info(payload)
        else:
            try:
                payload = json.loads(json_par)
                logger.info(payload)
            except json.decoder.JSONDecodeError:
                return response_failed("30000", "参数类型错误" + json_par)

        r = InterfaceRequest(str(data['api_method']), str(data['api_parameter_types']), api_url, header, payload,
                             data_payload)

        logger.info("测试用例名称： %s", data['api_test_case_name'])
        logger.info("请求地址： %s", r.url)
        logger.info("请求json数据： %s", payload)
        logger.info("请求parameter数据： %s", data_payload)
        logger.info("请求头： %s", r.headers)
        logger.info("请求响应： %s", r.text)

        logger.info(r.text)
        if r == "请求超时":
            return response_failed("30000", "接口超时", {'api_url': api_url,
                                                     "api_method": int(data['api_method']),
                                                     'api_header': header,
                                                     'api_body': payload,
                                                     'api_code': "请求超时",
                                                     'api_assert': "请求超时,断言失败",
                                                     'response_message': {"results": "请求超时"},
                                                     'response_time': 0,
                                                     'api_parameter_data': api_parameter})
        # r.encoding = r.apparent_encoding
        try:
            response_message = r.json()
        except json.decoder.JSONDecodeError:
            return response_failed("30000", "接口返回结果类型错误非JSON格式", {'api_url': api_url,
                                                                  "api_method": int(data['api_method']),
                                                                  'api_header': header,
                                                                  'api_body': payload,
                                                                  'api_code': str(r.status_code),
                                                                  'response_message': r.text,
                                                                  'response_time': str(r.elapsed.total_seconds()),
                                                                  'api_parameter_data': api_parameter})

        # 断言
        if data['api_assert_type'] == '':
            result = "断言内容为空"

        elif data['api_assert_type'] == 1:

            try:

                r_text = re.sub(r'(\\u[\s\S]{4})', lambda x: x.group(1).encode("utf-8").decode("unicode-escape"), r.text)

                r_text_test = "".join(r_text.split())
                r_text_data = "".join(data['api_assert_text'].split())
                assert r_text_data in r_text_test
                result = "断言成功"
            except Exception as e:
                result = "断言失败: 响应内容中未包含 断言内容，断言内容： %s ，响应内容：%s" % (
                    data['api_assert_text'], r_text_test)
                logger.error(result + str(e))
                pass

        elif data['api_assert_type'] == 2:
            try:
                r_text = re.sub(r'(\\u[\s\S]{4})', lambda x: x.group(1).encode("utf-8").decode("unicode-escape"), r.text)
                r_text_test = "".join(r_text.split())
                r_text_data = "".join(data['api_assert_text'].split())

                assert r_text_data == r_text_test
                result = "断言成功"
            except Exception as e:
                result = "断言失败: 断言内容 %s 与响应结果不匹配，%s" % (
                    data['api_assert_text'], r_text_test)
                logger.error(result + str(e))
                pass
        elif data['api_assert_type'] == 3:

            database = APIDatabase.objects.get(id=data['dataBase'])
            db = HandleDB(database.api_host, int(database.api_port), database.user, database.password,
                          database.database)
            sql = data['database_sql']
            count = db.get_count(sql)
            db.close()
            if str(count) == str(data['api_assert_text']):
                result = '断言成功'
            else:
                result = '断言失败,查询的数据是： %s' % str(count)
        elif data['api_assert_type'] == 4:
            try:
                assert data['api_assert_text'] == str(r.status_code)
                result = "断言成功"
            except Exception as e:
                result = "断言失败: code状态码 %s 与响应状态码不匹配，%s" % (data['api_assert_text'], str(r.status_code))
                logger.error(result + str(e))
                pass

        api_variable_results = []

        for api_parameter_extraction in data['api_parameter_extraction']:
            if api_parameter_extraction['api_value_variable'] == "":
                api_parameter_extraction_dict = {
                    "api_variable_results": "无参数提取",
                    "api_value_variable": api_parameter_extraction['api_value_variable'],
                    "api_key_variable": api_parameter_extraction['api_key_variable'],
                }
                api_variable_results.append(api_parameter_extraction_dict)

            elif ApiParameterExtraction.objects.filter(
                    api_key_variable=api_parameter_extraction['api_key_variable']).count() >= 0:
                # 提取变量
                try:
                    api_result = json.loads(r.text)
                except Exception as e:
                    logger.info('json转换失败（变量）：' + str(e))
                    pass
                v_text = api_parameter_extraction['api_value_variable'].split(".")
                logger.info('这是提取' + str(v_text))
                try:
                    api_result = ExtractParameters(v_text, api_result)
                    api_parameter_extraction_dict = {
                        "api_value_variable": api_parameter_extraction['api_value_variable'],
                        "api_key_variable": api_parameter_extraction['api_key_variable'],
                        "api_variable_results": str(api_result)
                    }

                    api_variable_results.append(api_parameter_extraction_dict)

                except Exception as e:
                    logger.info('参数提取异常' + str(e))
                    api_parameter_extraction_dict = {
                        "api_variable_results": api_parameter_extraction['api_key_variable'],
                        "api_value_variable": api_parameter_extraction['api_value_variable'],
                        "api_key_variable": api_parameter_extraction['api_key_variable'],
                    }

                    api_variable_results.append(api_parameter_extraction_dict)

                    logger.info(api_variable_results)
        return response_success({'api_url': api_url,
                                 'api_header': header,
                                 'api_body': payload,
                                 'api_code': str(r.status_code),
                                 'api_assert': str(result),
                                 "api_method": int(data['api_method']),
                                 'response_message': response_message,
                                 'response_time': str(r.elapsed.total_seconds()),
                                 'api_parameter_extraction': api_variable_results,
                                 'api_parameter_data': api_parameter})


class UploadTestCases(View):

    def post(self, request, *args, **kwargs):
        """
        上传API测试用例-excel
        """

        file_obj = request.FILES.get("file")
        name = file_obj.name
        fn = time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime())
        fn = fn + '-%d' % random.randint(0, 100)

        path = os.path.join(settings.API_TEST_CASE_ROOT, fn + '-' + name)

        with open(path, "wb") as f_write:
            for line in file_obj:
                f_write.write(line)

        return response_success({"file": 'http://' + request.get_host() + "/api/api_test_case_excel/" + fn + '-' + name,
                                 "result": "OK",
                                 "fileName": name,
                                 "path": path})

    def put(self, request, *args, **kwargs):
        """
        解析excel并创建测试用例
        :api_excel_name: 接口excel名称
        :param request:
        :param args:
        :param kwargs:
        :return:
        """
        upload_api_test_case_total = ""
        api_assert_type = ""
        api_parameter_types = ""
        api_method = ""
        body = request.body
        if not body:
            return response_success()
        data = json.loads(body)
        dir_test_case = settings.API_TEST_CASE_ROOT
        dir_list = os.listdir(dir_test_case)
        upload_results_list = []
        upload_api_test_case_id = []

        for api_test_case_excel in dir_list:
            if api_test_case_excel == str(data['upload_case_address_name']):

                api_excel = HandleExcel(dir_test_case + api_test_case_excel, 'Sheet1')

                api_cases = api_excel.read_all_datas()
                upload_api_test_case_total = len(api_cases)
                for i in range(len(api_cases)):
                    time.sleep(0.5)
                    # 获取项目id
                    try:
                        api_project_id = APIProject.objects.filter(
                            api_project_name=str(api_cases[i]['项目名称']).replace("\n", ""))
                    except Exception as e:
                        return response_failed(3001, message="excel格式错误，请重新上传")

                    # 获取模块id
                    api_module_id = APIModule.objects.filter(api_project_id=api_project_id[0].id,
                                                             api_module_name=str(api_cases[i]['模块']).replace("\n", ""))

                    if ApiTestCase.objects.filter(api_test_case_name=str(api_cases[i]['测试用例名称']).replace("\n", ""),
                                                  api_module_id=api_module_id[0].id).count() > 0:
                        upload_results_dict = {
                            "test_case_name": str(api_cases[i]['测试用例名称']).replace("\n", ""),
                            "api_module_name": str(api_cases[i]['模块']).replace("\n", ""),
                            "api_url": str(api_cases[i]['请求地址']).replace("\n", ""),
                            "api_project_name": str(api_cases[i]['项目名称']).replace("\n", ""),
                            "error_reason": "用例名称重复,请重新上传"
                        }
                        upload_results_list.append(upload_results_dict)
                        for test_case_id in upload_api_test_case_id:
                            ApiTestCase.objects.delete()
                        return response_failed(3000, {'status': 200, 'upload_results_list': upload_results_list,
                                                      'upload_api_test_case_total': upload_api_test_case_total,
                                                      'success_upload': '0', 'error_upload': len(upload_results_list),
                                                      "error_reason": "用例名称重复,请重新上传"})
                    # 获取域名id
                    api_environment_id = APIEnvironment.objects.filter(
                        api_title=(api_cases[i]['域名']).replace("\n", ""))

                    # 获取请求方式
                    if str(api_cases[i]['请求方式']).replace("\n", "").upper() == 'GET':
                        api_method = 1
                    elif str(api_cases[i]['请求方式']).replace("\n", "").upper() == 'POST':
                        api_method = 2
                    elif str(api_cases[i]['请求方式']).replace("\n", "").upper() == 'PUT':
                        api_method = 3
                    elif str(api_cases[i]['请求方式']).replace("\n", "").upper() == 'DELETE':
                        api_method = 4

                    # 获取body类型
                    # 1：form-data 2: json 3:x-www-form-urlencoded
                    if str(api_cases[i]['body类型']).replace("\n", "").upper() == 'FORM-DATA':
                        api_parameter_types = 1

                    elif str(api_cases[i]['body类型']).replace("\n", "").upper() == 'JSON':
                        api_parameter_types = 2

                    elif str(api_cases[i]['body类型']).replace("\n", "").upper() == 'X-WWW-FORM-URLENCODED':
                        api_parameter_types = 3

                    # 1：包含contains 2: 匹配MATHCHES 3:数据库校验SQL 4:CODE
                    if str(api_cases[i]['断言类型']).replace("\n", "").upper() == 'CONTAINS':
                        api_assert_type = 1

                    elif str(api_cases[i]['断言类型']).replace("\n", "").upper() == 'MATHCHES':
                        api_assert_type = 2

                    elif str(api_cases[i]['断言类型']).replace("\n", "").upper() == 'SQL':
                        api_assert_type = 3

                    elif str(api_cases[i]['断言类型']).replace("\n", "").upper() == 'CODE':
                        api_assert_type = 4

                    # 获取数据库
                    api_data_base_id = APIDatabase.objects.filter(
                        api_database_title=str(api_cases[i]['数据库环境']).replace("\n", ""))

                    if str(api_cases[i]['数据库环境']).replace("\n", "") == "None":
                        data_base_id = ""
                    else:
                        data_base_id = api_data_base_id[0].id

                    if str(api_cases[i]['数据库语句']).replace("\n", "") == "None":
                        database_sql = ""
                    else:
                        database_sql = str(api_cases[i]['数据库语句']).replace("\n", "")

                    # 获取body
                    if str(api_cases[i]['body']).replace("\n", "") == 'None':
                        api_parameter_body = {}
                    else:
                        api_parameter_body = str(api_cases[i]['body']).replace("\n", "")

                    # 获取请求头
                    if str(api_cases[i]['请求头']).replace("\n", "") == 'None':
                        header = {}
                    else:
                        header = str(api_cases[i]['请求头']).replace("\n", "")

                    # 获取断言内容
                    if str(api_cases[i]['断言内容']).replace("\n", "") == "None":
                        api_assert_text = ""
                    else:
                        api_assert_text = str(api_cases[i]['断言内容']).replace("\n", "")

                    # 创建测试用例
                    api_test_case = ApiTestCase.objects.create(
                        api_test_case_name=str(api_cases[i]['测试用例名称']).replace("\n", ""),
                        api_module_id=api_module_id[0].id,
                        api_documentation=api_cases[i]['接口文档地址'],
                        api_environment_id=api_environment_id[0].id,
                        api_method=api_method,
                        api_url=str(api_cases[i]['请求地址']).replace("\n", ""),
                        api_parameter_types=api_parameter_types,
                        api_headers=header,
                        api_parameter_body=api_parameter_body,
                        api_assert_type=api_assert_type,
                        dataBase_id=data_base_id,
                        database_sql=database_sql,
                        api_assert_text=api_assert_text
                    )

                    # 获取变量名称
                    variable_name = str(api_cases[i]['变量名称']).split(',')

                    # 获取变量提取表达式
                    api_value_variable = str(api_cases[i]['提取表达式']).split(',')

                    variable_name_list = []

                    for value in variable_name:
                        if ApiParameterExtraction.objects.filter(api_key_variable=value).count() > 0:
                            variable_name_dict = {
                                "api_key_variable": "变量名称重复" + str(value)
                            }
                            variable_name_list.append(variable_name_dict)
                            upload_results_dict = {
                                "test_case_name": str(api_cases[i]['测试用例名称']).replace("\n", ""),
                                "api_module_name": str(api_cases[i]['模块']).replace("\n", ""),
                                "api_url": str(api_cases[i]['请求地址']).replace("\n", ""),
                                "api_project_name": str(api_cases[i]['项目名称']).replace("\n", ""),
                                "error_reason": "参数变量重复,请重新上传"

                            }
                            upload_results_list.append(upload_results_dict)
                            for test_case_id in upload_api_test_case_id:
                                ApiTestCase.objects.delete()

                            return response_failed(3000, {'status': 200, 'upload_results_list': upload_results_list,
                                                          'upload_api_test_case_total': upload_api_test_case_total,
                                                          'success_upload': '0',
                                                          'error_upload': len(upload_results_list),
                                                          "error_reason": "参数变量重复,请重新上传"})

                        elif value == "None":
                            variable_name_list = []
                        else:
                            variable_name_dict = {
                                "api_key_variable": str(value)
                            }
                            variable_name_list.append(variable_name_dict)
                    for v in range(len(variable_name_list)):
                        if len(variable_name_list) == 0:
                            pass
                        else:
                            variable_name_list[v]['api_value_variable'] = api_value_variable[v]
                            ApiParameterExtraction.objects.create(
                                api_key_variable=variable_name_list[v]['api_key_variable'],
                                api_value_variable=api_value_variable[v], api_test_case_id=api_test_case.id)

                    # data参数 创建
                    if str(api_cases[i]['Params']).replace("\n", "") == "None":
                        ApiParameterData.objects.create(api_must_parameter="false",
                                                        api_test_case_id=api_test_case.id)
                    else:
                        params = json.loads(str(api_cases[i]['Params']).replace("\n", ""))
                        for key in params:
                            ApiParameterData.objects.create(api_parameter_name=key, api_must_parameter="true",
                                                            api_parameter_value=params[key],
                                                            api_test_case_id=api_test_case.id)

                    upload_api_test_case_id.append({'api_test_case_id': api_test_case.id})

        success_upload = upload_api_test_case_total - len(upload_results_list)

        return response_success({'status': 200, 'upload_results_list': upload_results_list,
                                 'upload_api_test_case_total': upload_api_test_case_total,
                                 'success_upload': success_upload, 'error_upload': len(upload_results_list)})


class DownloadApiCaseTemplate(View):

    def get(self, request, *args, **kwargs):
        """
        下载API用例模板
        :param request:
        :param args:
        :param kwargs:
        :return:
        """
        logger.info("API测试用例地址：" + settings.API_TEMPLATE)
        file = open(settings.API_TEMPLATE, 'rb')

        response = FileResponse(file)
        response['Content-Type'] = 'application/octet-stream'
        response['Content-Disposition'] = 'attachment;' + ' filename=' + "ApiTestCaseTemplate.xlsx"
        return response
