def startTaskByBatchCase(self, args):
        logger.info(args)
        isSuccess = True
        dataResult = DataResult()
        try:
            getCases = TestCaseDaoInterface().getCaseIds(args)
            if getCases.getSuccess():
                if len(getCases.getMessage()) > 0:
                    cases = getCases.getMessage()
                    for case in cases:
                        # caseId.setdefault("envName", args["envName"])
                        # dataResult = self.startTaskBySingleCase(caseId)
                        contents = CaseContentDaoInterface(
                        ).getContentInfosByCaseId(case)
                        caseResult = {}
                        #caseName = TestCaseDaoInterface().getCaseInfosById(caseId)
                        caseResult.setdefault("caseName", case["name"])
                        caseResult.setdefault("caseId", case["caseId"])
                        caseResult.setdefault("instanceId",
                                              args.get("instanceId"))
                        message = []
                        exec_start = time.time()
                        caseResult.setdefault("exec_start", exec_start)
                        if contents.getSuccess():
                            for content in contents.getMessage():
                                if int(content["method"]) == 0:
                                    method = "GET"
                                else:
                                    method = "POST"
                                if int(content["content_type"]) == 0:
                                    contentType = "application/json"
                                    if content[
                                            "requests_params"] is None or content[
                                                "requests_params"] == "":
                                        data = {}
                                    else:
                                        data = eval(content["requests_params"])
                                        data = json.dumps(data)
                                else:
                                    contentType = "application/x-www-form-urlencoded"
                                    if content[
                                            "requests_params"] is None or content[
                                                "requests_params"] == "":
                                        data = {}
                                    else:
                                        data = eval(content["requests_params"])
                                        data = data
                                if len(args["envName"]) > 0:
                                    environments = EnvironmentDaoInterface(
                                    ).getEnvironmentInfoByName(args)
                                    environment = environments.getMessage()[0]
                                    if environment[
                                            "pre_url"] is None or environment[
                                                "pre_url"] == "":
                                        if content[
                                                "webapi_path"] is None or content[
                                                    "webapi_path"] == "":
                                            logger.info("缺少接口path")
                                            continue
                                        else:
                                            if content[
                                                    "ip_url"] is None or content[
                                                        "ip_url"] == "":
                                                logger.info("缺少请求地址")
                                                continue
                                            else:
                                                url = content[
                                                    "ip_url"] + content[
                                                        "webapi_path"]
                                    else:
                                        if content[
                                                "webapi_path"] is None or content[
                                                    "webapi_path"] == "":
                                            logger.info("缺少接口path")
                                            continue
                                        else:
                                            url = environment[
                                                "pre_url"] + content[
                                                    "webapi_path"]

                                    if environment[
                                            "headers"] is None or environment[
                                                "headers"] == "":
                                        if content[
                                                "headers"] is None or content[
                                                    "headers"] == "":
                                            headers = {}
                                            headers.setdefault(
                                                "content-type", contentType)
                                        else:
                                            header = content["headers"]
                                            headers = eval(header)
                                            headers.setdefault(
                                                "content-type", contentType)
                                    else:
                                        header = environment["headers"]
                                        headers = eval(header)
                                        headers.setdefault(
                                            "content-type", contentType)
                                else:
                                    if content[
                                            "webapi_path"] is None or content[
                                                "webapi_path"] == "":
                                        logger.info("缺少接口path")
                                        continue
                                    else:
                                        if content["ip_url"] is None or content[
                                                "ip_url"] == "":
                                            logger.info("缺少请求地址")
                                            continue
                                        else:
                                            url = content["ip_url"] + content[
                                                "webapi_path"]
                                    if content["headers"] is None or content[
                                            "headers"] == "":
                                        headers = {}
                                        headers.setdefault(
                                            "content-type", contentType)
                                    else:
                                        header = content["headers"]
                                        headers = eval(header)
                                        headers.setdefault(
                                            "content-type", contentType)
                                requestUtil = RequestBase(url=url,
                                                          method=method,
                                                          data=data,
                                                          headers=headers)
                                response = requestUtil.httpRequest(
                                    url=url,
                                    method=method,
                                    data=data,
                                    headers=headers)
                                logger.info(response.text)
                                logger.info(response.status_code)
                                tmpArgs = {}
                                tmpArgs[content["step_name"]] = response.text
                                tmpArgs["status_code"] = response.status_code
                                tmpArgs[
                                    "elapsed_ms"] = response.elapsed.microseconds / 1000.0
                                message.append(tmpArgs)
                                #本处代码只是为了区别返回值为json还是view
                                try:
                                    data = json.loads(response.text)
                                except Exception as e:
                                    logger.warn(e)
                                    data = response.text

                                if response.status_code == 200:
                                    #此处需要验证用户自定义断言
                                    contentJson = {"contentId": content["id"]}
                                    assertInfos = AssertDaoInterface(
                                    ).getAssertInfosByContentId(contentJson)
                                    isFailed = False
                                    if assertInfos.getSuccess():
                                        for assertInfo in assertInfos.getMessage(
                                        ):
                                            actual = CommonTool().render(
                                                template=assertInfo["actual"],
                                                data=data,
                                                status=response.status_code)
                                            if not AssertService().routeAssert(
                                                    actual,
                                                    assertInfo["expect"],
                                                    assertInfo["assert_type"]):
                                                isFailed = True
                                    if not isFailed:
                                        caseResult.setdefault(
                                            "exe_status", "success")
                                    else:
                                        caseResult.setdefault(
                                            "exe_status", "fail")
                                else:
                                    caseResult.setdefault("exe_status", "fail")
                                    isSuccess = False
                            caseResult.setdefault("message", str(message))
                            caseResult.setdefault(
                                "runtime", (time.time() - exec_start) * 1000)
                            logger.info(caseResult)
                            createCaseResult = CaseResultDaoInterface(
                            ).addCaseResult(caseResult)
                            logger.info(createCaseResult.getSuccess())
                            logger.info(createCaseResult.getMessage())
                else:
                    dataResult.setMessage("项目中无可执行的用例")
                    isSuccess = False
            else:
                dataResult.setMessage("获取用例失败")
                isSuccess = False
            if isSuccess:
                args["status"] = 2
            else:
                args["status"] = 3
            TestCaseInstanceDaoInterface().updateTestInstanceStatus(args)
            return dataResult
        except Exception as err:
            logger.info(err)
            args["status"] = 4
            TestCaseInstanceDaoInterface().updateTestInstanceStatus(args)
            dataResult.setMessage("程序运行异常")
            return dataResult
 def __execTaskJob(taskInfo):
     taskInstanceId = taskInfo.get("instanceid")
     logger.info("exec task [{0}]:".format(taskInstanceId))
     args = {}
     args.setdefault("instanceId", taskInstanceId)
     args.setdefault("build_start", datetime.datetime.now())
     result = DataResult()
     taskGlobalStatus = "Error"
     try:
         #set metaq queue status is received
         metaq_args = {}
         metaq_args.setdefault("status", "2")
         #hostname
         hostname = socket.gethostname()
         ip = socket.gethostbyname(hostname)
         metaq_args.setdefault("running_consumer",
                               "{0}|{1}".format(ip, hostname))
         metaq_args.setdefault("msg_id", os.getpid())
         metaq_args.setdefault("taskId", taskInfo.get("id"))
         TaskMetaqInfoDaoInterface().updateTaskInfo(metaq_args)
         #query task instance info by id
         logger.info("query task instance [{0}] ...".format(taskInstanceId))
         dataResult = TestCaseInstanceDaoInterface(
         ).getTestInstanceInfoById(args)
         if dataResult.getSuccess() and len(dataResult.getMessage()) > 0:
             suiteId = dataResult.getMessage()[0].get("suite_id")
             userId = dataResult.getMessage()[0].get("create_userid")
             #set instance Running
             args.setdefault("build_end", None)
             args.setdefault("status", "Running")
             TestCaseInstanceDaoInterface().updateTestInstance(args)
             logger.info("query suite [{0}]by instance [{1}] ...".format(
                 suiteId, taskInstanceId))
             dataResult = TestSuiteDaoInterface().getSuiteInfoById(
                 {"suiteId": suiteId})
             if dataResult.getSuccess() and len(
                     dataResult.getMessage()) > 0:
                 envId = dataResult.getMessage()[0].get("envid")
                 caseIds = dataResult.getMessage()[0].get("testcaseids")
                 #get global env param
                 envResult = EnvironmentDaoInterface(
                 ).getEnvironmentInfoById({"envId": envId})
                 if envResult.getSuccess() and len(
                         envResult.getMessage()) <= 0:
                     logger.error(
                         "Test suite [{0}]:No env config".format(suiteId))
                     taskGlobalStatus = "Failed"
                     return result
                 if caseIds is None or len(caseIds) == 0:
                     logger.info("Test suite [{0}]:No case".format(suiteId))
                     taskGlobalStatus = "Success"
                 else:
                     # get init case for save session
                     initResult = TaskCenterService.__getInitCaseJob(
                         caseIds)
                     if not initResult.getSuccess():
                         logger.error(
                             "Test suite [{0}]:No init case".format(
                                 suiteId))
                         taskGlobalStatus = "Failed"
                         return result
                     initCaseInfo = initResult.getMessage()[0]
                     initCaseId = initCaseInfo.get("id")
                     #return request Object
                     initRequest = TaskCenterService.__execTaskCaseJob(
                         initCaseId, userId, envResult[0], None, True,
                         taskInstanceId, "init")
                     for caseId in list(caseIds):
                         if caseId == initCaseId:
                             continue
                         dataResult = TestCaseInstanceDaoInterface(
                         ).getTestInstanceInfoById(args)
                         if dataResult.getMessage()[0].get(
                                 "status") not in ["Stopped", "TimeOut"]:
                             execResult = TaskCenterService.__execTaskCaseJob(
                                 caseId, None, envResult[0],
                                 initRequest.getMessage(), True,
                                 taskInstanceId, None)
                             if not execResult.getSuccess():
                                 #set instance db
                                 taskGlobalStatus = execResult.getMessage()
                                 return result
                         else:
                             logger.error(
                                 "Task instance [{0}] is stopped".format(
                                     args.get("instanceId")))
                             taskGlobalStatus = dataResult.getMessage(
                             )[0].get("status")
                             return result
                     taskGlobalStatus = "Success"
                     result.setSuccess(True)
                     return result
     except Exception as e:
         logger.error("Exception:{0}".format(traceback.format_exc()))
         return result
     finally:
         args.setdefault("build_end", datetime.datetime.now())
         args.setdefault("status", taskGlobalStatus)
         TestCaseInstanceDaoInterface().updateTestInstance(args)
    def startTaskBySingleCase(self, args):
        message = []
        logger.info(args)
        contents = CaseContentDaoInterface().getContentInfosByCaseId(args)

        if contents.getSuccess():
            for content in contents.getMessage():

                if int(content["method"]) == 0:
                    method = "GET"
                else:
                    method = "POST"
                if int(content["content_type"]) == 0:
                    contentType = "application/json"
                    if content["requests_params"] is None or content[
                            "requests_params"] == "":
                        data = {}
                    else:
                        data = eval(content["requests_params"])
                        data = json.dumps(data)
                else:
                    contentType = "application/x-www-form-urlencoded"
                    if content["requests_params"] is None or content[
                            "requests_params"] == "":
                        data = {}
                    else:
                        data = eval(content["requests_params"])
                        data = data

                if len(args["envName"]) > 0:
                    environments = EnvironmentDaoInterface(
                    ).getEnvironmentInfoByName(args)
                    environment = environments.getMessage()[0]
                    logger.info(environment["pre_url"])
                    if environment["pre_url"] is None or environment[
                            "pre_url"] == "":
                        if content["webapi_path"] is None or content[
                                "webapi_path"] == "":
                            contents.setSuccess(False)
                            contents.setMessage("缺少请求接口path")
                            return contents
                        else:
                            if content["ip_url"] is None or content[
                                    "ip_url"] == "":
                                contents.setSuccess(False)
                                contents.setMessage("缺少请求地址")
                                return contents
                            else:
                                url = content["ip_url"] + content["webapi_path"]
                    else:
                        if content["webapi_path"] is None or content[
                                "webapi_path"] == "":
                            contents.setSuccess(False)
                            contents.setMessage("缺少请求接口path")
                            return contents
                        else:
                            url = environment["pre_url"] + content[
                                "webapi_path"]

                    if environment["headers"] is None or environment[
                            "headers"] == "":
                        if content["headers"] is None or content[
                                "headers"] == "":
                            headers = {}
                            headers.setdefault("content-type", contentType)
                        else:
                            header = content["headers"]
                            headers = eval(header)
                            headers.setdefault("content-type", contentType)
                    else:
                        header = environment["headers"]
                        headers = eval(header)
                        headers.setdefault("content-type", contentType)
                else:
                    if content["webapi_path"] is None or content[
                            "webapi_path"] == "":
                        contents.setSuccess(False)
                        contents.setMessage("缺少请求接口path")
                        return contents
                    else:
                        if content["ip_url"] is None or content["ip_url"] == "":
                            contents.setSuccess(False)
                            contents.setMessage("缺少请求地址")
                            return contents
                        else:
                            url = content["ip_url"] + content["webapi_path"]
                    if content["headers"] is None or content["headers"] == "":
                        headers = {}
                        headers.setdefault("content-type", contentType)
                    else:
                        header = content["headers"]
                        headers = eval(header)
                        headers.setdefault("content-type", contentType)

                requestUtil = RequestBase(url=url,
                                          method=method,
                                          data=data,
                                          headers=headers)
                response = requestUtil.httpRequest(url=url,
                                                   method=method,
                                                   data=data,
                                                   headers=headers)
                tmpArgs = {}
                tmpArgs[content["step_name"]] = response.text
                message.append(tmpArgs)
            logger.error(message)
            contents.setSuccess(True)
            contents.setMessage(message)
            contents.setStatusCode(200)
        else:
            contents.setSuccess(False)
            contents.setMessage("获取用例内容失败")
        return contents
 def __execTaskCaseJob(caseId,userId=None,envConfig=False,requestObject=None,init=False, \
                       instanceId=None,caseName=None):
     if not envConfig:
         caseInfo = TestCaseDaoInterface().getCaseInfosById(
             {"caseId", caseId})
         if caseInfo.getSuccess() and len(caseInfo.getMessage()) > 0:
             envId = caseInfo.getMessage()[0].get("envid")
             envResult = EnvironmentDaoInterface().getEnvironmentInfoById(
                 {"envId": envId})
             if envResult.getSuccess() and len(envResult.getMessage()) <= 0:
                 logger.error(
                     "Test envId [{0}]:No env config".format(envId))
                 return
             envConfig = envResult[0]
         else:
             return
     if init:
         saveSession = False
     elif requestObject is not None:
         saveSession = False
     else:
         saveSession = True
     exec_start_flag = time.time()
     exec_start = datetime.datetime.now()
     contentResult = CaseContentDaoInterface().getContentInfosByCaseId(
         caseId)
     Presult = {}
     statusFlag = True
     if contentResult.getSuccess() and len(contentResult.getMessage()) > 0:
         for content in sorted(contentResult.getMessage(),
                               key=attrgetter('step')):
             #TODO "DATARESULT" + STEP
             response = None
             #request api
             if content.get("type") == 0:
                 if envConfig.get("datatemplate").endswith("/"):
                     url = envConfig.get("datatemplate")[:-1] + content.get(
                         "url")
                 else:
                     url = envConfig.get("datatemplate") + content.get(
                         "url")
                 params = TaskCenterService.__rendeTemplate(
                     content.get("request_params"),
                     envConfig.get("datatemplate"), Presult)
                 requestUtil = RequestBase(url=url,
                                           method=content.get("method"),
                                           format=content.get("format"),
                                           params=params,
                                           object=requestObject,
                                           userId=userId,
                                           saveSession=saveSession)
                 response, obj = requestUtil.route()
                 try:
                     response = json.loads(response)
                 except Exception as e:
                     logger.warn(
                         "return result is not json:{0} Exception:{1}".
                         format(response, e))
             #request sql
             elif content.get("type") == 1:
                 dbConfig = {}
                 dbConfig.setdefault("db", envConfig.get("dbname"))
                 dbConfig.setdefault("host", envConfig.get("dbhostname"))
                 dbConfig.setdefault("user", envConfig.get("dbusername"))
                 dbConfig.setdefault("passwd", envConfig.get("dbpasswd"))
                 dbConfig.setdefault("port", envConfig.get("dbport"))
                 dbUtil = DbBaseHelper()
                 response = dbUtil.execReadOnlySQL(
                     dbConfig,
                     TaskCenterService.__rendeTemplate(
                         content.get("sqlcontent"),
                         envConfig.get("datatemplate"), Presult, False))
             Presult.setdefault("DATAREAULT" + str(content.get("step")),
                                response)
             #assert
             assertResult = AssertDaoInterface().getAssertInfosByContentId(
                 content.get("id"))
             if assertResult.getSuccess():
                 for assertInfo in assertResult:
                     result = TaskCenterService.__execAssertJob(
                         eval("Presult." + assertInfo.get("actual")),
                         assertInfo.get("expect"),
                         assertInfo.get("assert_type"))
                     if not result.getSuccess():
                         statusFlag = False
                         break
     if saveSession:
         exec_end_flag = time.time()
         exec_end = datetime.datetime.now()
         if statusFlag:
             status = "Success"
         else:
             status = "Failed"
         #caseResult
         caseResultInfo = {}
         caseResultInfo.setdefault("instanceid", instanceId)
         caseResultInfo.setdefault("caseid", caseId)
         caseResultInfo.setdefault("casename", caseName)
         caseResultInfo.setdefault("runtime",
                                   exec_end_flag - exec_start_flag)
         caseResultInfo.setdefault("exec_start", exec_start)
         caseResultInfo.setdefault("exec_end", exec_end)
         caseResultInfo.setdefault("status", status)
         caseResultInfo.setdefault("messaga", response)
         caseResultInfo.setdefault("remarks", None)
         CaseResultDaoInterface().addCaseResult(caseResultInfo)
     dataResult = DataResult()
     dataResult.setSuccess(statusFlag)
     if init:
         dataResult.setMessage(obj)
     else:
         dataResult.setMessage(status)
     return dataResult
 def __init__(self):
     self.EnvironmentDaoInterface = EnvironmentDaoInterface()
class EnvironmentService(object):
    def __init__(self):
        self.EnvironmentDaoInterface = EnvironmentDaoInterface()

    @AdminDecoratorServer.execImplDecorator()
    def addEnvironmentItem(self, args):
        return self.EnvironmentDaoInterface.addEnvironmentItem(args)

    @AdminDecoratorServer.execImplDecorator()
    def getEnvironmentInfoById(self, envId):
        args = {}
        args.setdefault("envId", envId)
        return self.EnvironmentDaoInterface.getEnvironmentInfoById(args)

    @AdminDecoratorServer.execImplDecorator()
    def getEnvironmentInfosByUserId(self, userId):
        args = {}
        args.setdefault("userId", userId)
        return self.EnvironmentDaoInterface.getEnvironmentInfosByUserId(args)

    @AdminDecoratorServer.execImplDecorator()
    def deleteEnvironmentItem(self, args):
        return self.EnvironmentDaoInterface.deleteEnvironmentItem(args)

    def editEnvironmentItem(self, args):
        if "template" not in args:
            args.setdefault("template", None)
        else:
            if not isinstance(args.get("template"), dict):
                try:
                    #验证data模板是否为json
                    logger.info("template is not dict:{0}".format(
                        args.get("template")))
                    datatemplate = json.dumps(json.loads(args.get("template")))
                    args.pop("template")
                    args.setdefault("template", datatemplate)
                except Exception as e:
                    logger.error(traceback.format_exc())
                    dataResult = DataResult()
                    dataResult.setMessage(
                        "template param [{0}]is invalid, must be dict".format(
                            args.get("template")))
                    dataResult.setSuccess(False)
                    return dataResult
            else:
                logger.info("template is dict:{0}".format(
                    args.get("template")))
                datatemplateJSONString = json.dumps(args.get("template"))
                args.pop("template")
                args.setdefault("template", datatemplateJSONString)
        if "headers" not in args:
            args.setdefault("headers", None)
        else:
            if not isinstance(args.get("headers"), dict):
                try:
                    #验证authInfo是否为json
                    logger.info("headers is not dict:{0}".format(
                        args.get("headers")))
                    datatemplate = json.dumps(json.loads(args.get("headers")))
                    args.pop("headers")
                    args.setdefault("headers", datatemplate)
                except Exception as e:
                    logger.error(traceback.format_exc())
                    dataResult = DataResult()
                    dataResult.setMessage(
                        "headers param [{0}]is invalid, must be dict".format(
                            args.get("headers")))
                    dataResult.setSuccess(False)
                    return dataResult
            else:
                logger.info("headers is dict:{0}".format(args.get("headers")))
                datatemplateJSONString = json.dumps(args.get("headers"))
                args.pop("headers")
                args.setdefault("headers", datatemplateJSONString)
        if "authInfo" not in args:
            args.setdefault("authInfo", None)
        else:
            if not isinstance(args.get("authInfo"), dict):
                try:
                    #验证authInfo是否为json
                    logger.info("authInfo is not dict:{0}".format(
                        args.get("authInfo")))
                    datatemplate = json.dumps(json.loads(args.get("authInfo")))
                    args.pop("authInfo")
                    args.setdefault("authInfo", datatemplate)
                except Exception as e:
                    logger.error(traceback.format_exc())
                    dataResult = DataResult()
                    dataResult.setMessage(
                        "authInfo param [{0}]is invalid, must be dict".format(
                            args.get("authInfo")))
                    dataResult.setSuccess(False)
                    return dataResult
            else:
                logger.info("authInfo is dict:{0}".format(
                    args.get("authInfo")))
                datatemplateJSONString = json.dumps(args.get("authInfo"))
                args.pop("authInfo")
                args.setdefault("authInfo", datatemplateJSONString)

        dataResult = self.EnvironmentDaoInterface.getEnvironmentInfoById(args)
        if dataResult.getSuccess() and len(dataResult.getMessage()) > 0:
            for key, value in dataResult.getMessage()[0].items():
                if key not in args:
                    args.setdefault(key, value)
            return self.EnvironmentDaoInterface.editEnvironmentItem(args)
        dataResult.setMessage("apiId [{0}] is invalid".format(
            args.get("envId")))
        return dataResult

    def getEnvironmentInfos(self):
        return self.EnvironmentDaoInterface.getEnvironmentInfos()
Exemple #7
0
class EnvironmentService(object):
    def __init__(self):
        self.EnvironmentDaoInterface = EnvironmentDaoInterface()

    @AdminDecoratorServer.execImplDecorator()
    def addEnvironmentItem(self, args):
        if "url" not in args:
            args.setdefault("url", None)
        if "template" not in args:
            args.setdefault("template", None)
        else:
            if not isinstance(args.get("template"), dict):
                try:
                    #验证data模板是否为json
                    logger.info("template is not dict:{0}".format(
                        args.get("template")))
                    datatemplate = json.dumps(json.loads(args.get("template")))
                    # logger.error(datatemplate)
                    # logger.error(type(datatemplate))
                    args.pop("template")
                    args.setdefault("template", datatemplate)
                except Exception:
                    logger.error(traceback.format_exc())
                    dataResult = DataResult()
                    dataResult.setMessage(
                        "template param [{0}]is invalid, must be dict".format(
                            args.get("template")))
                    dataResult.setSuccess(False)
                    return dataResult
            else:
                logger.info("template is dict:{0}".format(
                    args.get("template")))
                datatemplateJSONString = json.dumps(args.get("template"))
                # logger.error(datatemplateJSONString)
                args.pop("template")
                args.setdefault("template", datatemplateJSONString)
        if "dbname" not in args:
            args.setdefault("dbname", None)
        if "dbhostname" not in args:
            args.setdefault("dbhostname", None)
        if "dbport" not in args:
            args.setdefault("dbport", None)
        if "dbusername" not in args:
            args.setdefault("dbusername", None)
        if "dbpasswd" not in args:
            args.setdefault("dbpasswd", None)
        return self.EnvironmentDaoInterface.addEnvironmentItem(args)

    @AdminDecoratorServer.execImplDecorator()
    def getEnvironmentInfoById(self, envId):
        args = {}
        args.setdefault("envId", envId)
        return self.EnvironmentDaoInterface.getEnvironmentInfoById(args)

    @AdminDecoratorServer.execImplDecorator()
    def getEnvironmentInfosByUserId(self, userId):
        args = {}
        args.setdefault("userId", userId)
        return self.EnvironmentDaoInterface.getEnvironmentInfosByUserId(args)

    @AdminDecoratorServer.execImplDecorator()
    def deleteEnvironmentItem(self, args):
        return self.EnvironmentDaoInterface.deleteEnvironmentItem(args)

    def editEnvironmentItem(self, args):
        if "template" not in args:
            args.setdefault("template", None)
        else:
            if not isinstance(args.get("template"), dict):
                try:
                    #验证data模板是否为json
                    logger.info("template is not dict:{0}".format(
                        args.get("template")))
                    datatemplate = json.dumps(json.loads(args.get("template")))
                    args.pop("template")
                    args.setdefault("template", datatemplate)
                except Exception, err:
                    logger.error(traceback.format_exc())
                    dataResult = DataResult()
                    dataResult.setMessage(
                        "template param [{0}]is invalid, must be dict".format(
                            args.get("template")))
                    dataResult.setSuccess(False)
                    return dataResult
            else: