Beispiel #1
0
def check_user(user_id):
    api_logger.debug("准备查询缓存账户数据")
    # 尝试从mysql中查询
    try:
        api_logger.debug("准备查询账户数据")
        uinfo_mysql = model_mysql_userinfo.query.filter_by(
            userId=user_id).first()
        api_logger.debug("账户数据查询成功")
    except Exception as e:
        api_logger.error("账户数据查询失败,失败原因:" + repr(e))
        return False
    else:
        # 如果mysql中未查询到
        if uinfo_mysql is None:
            return False
        # 如果mysql中查询到了
        else:
            # 判断账户状态
            if uinfo_mysql.userStatus == 0:
                return False
            elif uinfo_mysql.userStatus == -1:
                return False
            elif uinfo_mysql.userStatus != 1:
                return False
    return True
Beispiel #2
0
def key_case_delete():
    # 初始化返回内容
    response_json = {"code": 200, "msg": "数据删除成功", "data": None}

    # 取出必传入参
    request_user_id = flask.request.headers['UserId']
    case_id = flask.request.args['id']

    # 查用例是否存在,构造基础信息
    try:
        mysql_case_info = model_mysql_case.query.filter(
            model_mysql_case.id == case_id,
            model_mysql_case.type == 2).first()
    except Exception as e:
        api_logger.error("测试计划类型读取失败,失败原因:" + repr(e))
        return route.error_msgs[500]['msg_db_error']
    else:
        if mysql_case_info is None:
            return route.error_msgs[201]['msg_no_case']
        else:
            indexchang(mysql_case_info.index, mysql_case_info.columnId)
            mysql_case_info.status = -1
            mysql_case_info.updateUserId = request_user_id
            mysql_case_info.index = 0
            mysqlpool.session.commit()

            # 添加日志

            case_logs = model_mysql_caseEditLog(caseId=mysql_case_info.id,
                                                type=7)
            mysqlpool.session.add(case_logs)
            mysqlpool.session.commit()

    return response_json
Beispiel #3
0
def create_snap_when_close(plan_id):
    redis_get_table_bytes = modle_redis_apitestplanworktable.query_table(
        plan_id)
    if redis_get_table_bytes is not None:
        # mysql中新增snap
        # 将status为1的snap全部置为失效
        try:
            model_mysql_tablesnap.query.filter(
                and_(model_mysql_tablesnap.planId == plan_id,
                     model_mysql_tablesnap.status == 1)).update({"status": 0})
            mysqlpool.session.commit()
        except Exception as e:
            api_logger.error("model_mysql_tablesnap数据更新失败,失败原因:" + repr(e))
            return False
        else:
            api_logger.debug("model_mysql_tablesnap数据更新成功")
            try:
                mysqlpool.session.add(
                    model_mysql_tablesnap(
                        status=1,
                        planId=plan_id,
                        snapAddTime=datetime.datetime.now(),
                        table=redis_get_table_bytes.decode('utf-8')))
                mysqlpool.session.commit()
            except Exception as e:
                api_logger.error("mysql_snaps数据写入失败,失败原因:" + repr(e))
            else:
                api_logger.debug("mysql_snaps数据写入成功")
            finally:
                # 不管如何,清空redis中的数据
                delete_flag = modle_redis_apitestplanworktable.delete(plan_id)
                api_logger.debug(
                    "redis中缓存清除完毕") if delete_flag else api_logger.debug(
                        "redis中缓存清除失败")
Beispiel #4
0
def conflictDtail(conflict_id):
    response_conflict = {"detail": []}
    # 判断项目冲突是否存在
    try:
        mysql_conflict_info = model_mysql_projectArchivePendingCase.query.filter(
            model_mysql_projectArchivePendingCase.id == conflict_id,
            model_mysql_projectArchivePendingCase.status == 1).first()
    except Exception as e:

        api_logger.error("读取失败,失败原因:" + repr(e))
        return route.error_msgs[500]['msg_db_error']
    else:
        if mysql_conflict_info is None:
            return response_conflict

    # 构造冲突结果返回信息
    originalCase = []
    projectIdCase = []
    otherCase = []
    originalCase.append(createcase(mysql_conflict_info.originalCaseId))
    projectIdCase.append(createcase(mysql_conflict_info.projectIdCaseId))
    otherCase.append(createcase(mysql_conflict_info.otherCaseId))
    response_conflict["detail"].append({
        "id": mysql_conflict_info.id,
        "projectId": mysql_conflict_info.projectId,
        "originalCase": originalCase,
        "projectIdCase": projectIdCase,
        "otherCase": otherCase,
        "status": mysql_conflict_info.status
    })

    return response_conflict
Beispiel #5
0
def precondition(caseid, case_precondition):
    # 更新分多种场景
    try:
        case_Precondition = model_mysql_casePrecondition.query.filter(
            model_mysql_casePrecondition.caseId == caseid
        ).first()
    except Exception as e:
        api_logger.error("测试计划类型读取失败,失败原因:" + repr(e))
        return route.error_msgs[500]['msg_db_error']
    else:
        # 原来为空,现在也为空不更新,现在非空则插入数据
        if case_Precondition is None:
            if len(case_precondition) == 0:
                pass
            else:
                new_casePrecondition_info = model_mysql_casePrecondition(
                    content=case_precondition,
                    caseId=caseid
                )
                mysqlpool.session.add(new_casePrecondition_info)
                mysqlpool.session.commit()
        else:
            # 原来不为空,现在为空/非空直接更新即可
            case_Precondition.content = case_precondition
            mysqlpool.session.commit()
Beispiel #6
0
 def wrapper(*args, **kwargs):
     request_url = flask.request.url
     api_logger.debug("URL:" + request_url + ".准备检查请求格式")
     try:
         request_parameters = flask.request.json
     except Exception as e:
         api_logger.error("URL:" + request_url + "格式检查失败,原因:" + repr(e))
         return error_msgs[301]['msg_request_body_not_json']
     else:
         if not request_parameters:
             return error_msgs[301]['msg_request_body_not_json']
     # 检查必传项目
     for key in keys:
         # 如果缺少必传项
         if key[0] not in request_parameters:
             return error_msgs[302]['msg_request_params_incomplete']
         else:
             value = request_parameters[key[0]]
             # 先检查类型
             if type(value) is not key[1]:
                 return error_msgs[301]['msg_value_type_error']
             # 如果非布尔型,则检查长度
             if key[1] is not bool:
                 # 如果有最小值但没最大值
                 if key[2] and not key[3]:
                     if key[1] is str or key[1] is list:
                         # 如果比最小值还小
                         if len(value) < key[2]:
                             return error_msgs[301][
                                 'msg_value_type_error']
                     elif key[1] is int:
                         # 如果比最小值还小
                         if value < key[2]:
                             return error_msgs[301][
                                 'msg_value_type_error']
                 # 如果有最小以及最大值
                 elif key[2] and key[3]:
                     if key[1] is str or key[1] is list:
                         # 如果比最小值还小或者比最大值还大
                         if len(value) < key[2] or len(value) > key[3]:
                             return error_msgs[301][
                                 'msg_value_type_error']
                     elif key[1] is int:
                         # 如果比最小值还小或者比最大值还大
                         if value < key[2] or value > key[3]:
                             return error_msgs[301][
                                 'msg_value_type_error']
                 # 如果有没有最小值但有最大值
                 elif not key[2] and key[3]:
                     if key[1] is str or key[1] is list:
                         # 如果比最大值还大
                         if len(value) > key[3]:
                             return error_msgs[301][
                                 'msg_value_type_error']
                     elif key[1] is int:
                         # 如果比最大值还大
                         if value > key[3]:
                             return error_msgs[301][
                                 'msg_value_type_error']
     return func(*args, **kwargs)
Beispiel #7
0
 def wrapper(*args, **kwargs):
     # 首先检查必传参数Mail/Token
     if 'UserId' not in flask.request.headers:
         return error_msgs[302]['msg_request_params_incomplete']
     user_id = flask.request.headers['UserId']
     # 尝试从mysql中查询
     try:
         api_logger.debug("准备查询账户数据")
         uinfo_mysql = model_mysql_userinfo.query.filter_by(
             userId=user_id).first()
         api_logger.debug("账户数据查询成功")
     except Exception as e:
         api_logger.error("账户数据查询失败,失败原因:" + repr(e))
         return error_msgs[500]['msg_db_error']
     else:
         # 如果mysql中未查询到
         if uinfo_mysql is None:
             return error_msgs[201]['msg_no_user']
         # 如果mysql中查询到了
         else:
             # 判断账户状态
             if uinfo_mysql.userStatus == 0:
                 return error_msgs[201]['msg_need_register']
             elif uinfo_mysql.userStatus == -1:
                 return error_msgs[201]['msg_user_forbidden']
             elif uinfo_mysql.userStatus != 1:
                 return error_msgs[201]['msg_status_error']
     # 检查通过,执行应用逻辑
     return func(*args, **kwargs)
Beispiel #8
0
def check_token(userId, token):
    # 去缓存的token中查询Mail,不存在的话即为从来没登陆过
    # redis查询无错误信息,不作try处理
    api_logger.debug("准备查询缓存token数据")
    tdata = model_redis_usertoken.query(userId)
    if tdata is None:
        api_logger.debug("缓存token数据为空")
        return False
    else:
        api_logger.debug("缓存token数据存在")
        # 格式化缓存基础信息内容
        try:
            t = json.loads(tdata.decode("utf8"))
            api_logger.debug("缓存token数据json格式化成功")
        except Exception as e:
            api_logger.error("缓存token数据json格式化失败,失败原因:" + repr(e))
            return False
        # 判断是否一致且有效
        # 判断是否过期
        if token != t["userToken"]:
            return False
        elif datetime.datetime.strptime(
                t["validTime"], "%Y-%m-%d %H:%M:%S") < datetime.datetime.now():
            return False
    # 检查通过,返回True
    return True
Beispiel #9
0
 def check_code(cls, userid, code, operationid):
     # 校验账户的操作记录
     # 查询mysql
     try:
         rdata_mysql = model_mysql_useroperationrecord.query.filter_by(
             userId=userid,
             operationId=operationid,
             recordStatus=0
         ).first()
     except Exception as e:
         logmsg = "数据库中账户操作记录读取失败,失败原因:" + repr(e)
         api_logger.error(logmsg)
         return None, None
     # 如果未查询到
     if rdata_mysql is None:
         return False, None
     # 如果查询到了
     else:
         record_code = rdata_mysql.recordCode
         record_validtime = rdata_mysql.recordValidTime
         # 如果不一致
         if code != record_code:
             return False, None
         elif datetime.datetime.now() > record_validtime:
             return True, 0
         else:
             return True, 1
Beispiel #10
0
def key_project_put():
    # 初始化返回内容
    response_json = {"code": 200, "msg": "数据修改成功", "data": None}

    # 取出必传入参
    request_user_id = flask.request.headers['UserId']
    project_name = flask.request.json['name']
    project_description = flask.request.json['description']
    project_coverOssPath = flask.request.json['coverOssPath']
    project_id = flask.request.json['id']

    # 查询项目名称是否存在
    try:
        mysql_project = model_mysql_project.query.filter(
            model_mysql_project.id == project_id,
            model_mysql_project.status == 1).first()
    except Exception as e:
        api_logger.error("项目数据读取失败,失败原因:" + repr(e))
        return route.error_msgs[500]['msg_db_error']

    if mysql_project is None:
        return route.error_msgs[201]['msg_no_project']
    else:
        mysql_project.name = project_name
        mysql_project.description = project_description
        mysql_project.coverOssPath = project_coverOssPath

    try:
        mysqlpool.session.commit()
    except Exception as e:
        api_logger.error("项目数据更新失败,失败原因:" + repr(e))
        return route.error_msgs[500]['msg_db_error']

    # 最后返回内容
    return response_json
Beispiel #11
0
def get_task_init_logs(task_id, query_offset=0, query_limit=200):
    """
    至mongodb中获取re_task_id对应的初始化日志条目,并将条目组装为单个字符串
    顺序获取
    每次获取N条,并记录下当前获取的条目数
    循环请求时仅返回批次数据,之前返回的不再返回,保证接口每批次返回数据较小
    :param task_id: 测试任务id
    :param query_offset: 分页查询偏移量
    :param query_limit: 分页查询行数
    :return:
        True/False-方法执行结果
        initLog/None-测试任务初始化日志
        count/None-数据总数
    """
    try:
        log_query = mongodb_tasklog_pool['task%s_init' % task_id].find({}, {
            "_id": 0,
            "log": 1
        }).skip(query_offset).limit(query_limit)
    except Exception as e:
        api_logger.error("测试任务:%s初始化日志数据读取失败,失败原因:%s" % (task_id, repr(e)))
        return False, None, -1
    else:
        api_logger.debug("测试任务:%s初始化日志数据读取成功" % task_id)
        log_list = [lq['log'] for lq in list(log_query)]
        return True, log_list, log_query.count()
Beispiel #12
0
def key_project_delete():
    # 初始化返回内容
    response_json = {"code": 200, "msg": "数据删除成功", "data": None}

    # 取出入参
    project_user_id = flask.request.headers['UserId']
    project_id = flask.request.args['id']

    # 判断项目是否存在
    try:
        mysql_project_info = model_mysql_project.query.filter(
            model_mysql_project.id == project_id,
            model_mysql_project.userId == project_user_id,
            model_mysql_project.status == 1).first()
        api_logger.debug("账户基础信息读取成功")
    except Exception as e:
        api_logger.error("账户基础信息读取失败,失败原因:" + repr(e))
        return route.error_msgs[500]['msg_db_error']
    else:
        if mysql_project_info is None:
            return route.error_msgs[201]['msg_no_project']
        else:
            mysql_project_info.status = -1
            mysqlpool.session.commit()

    # 最后返回内容
    return response_json
Beispiel #13
0
def get_snap_table_data(plan_id):

    # 于redis中尝试读取计划的快照缓存
    cache_table_bytes = modle_redis_apitestplanworktable.query_table(
        plan_id=plan_id)

    # 如果缓存中没有,就去mysql读取并且同步至redis
    # 这里类型错误,数组为空
    if cache_table_bytes is None:
        # 读取mysql中对应plan的最新snap
        try:
            mysql_snap_data = model_mysql_tablesnap.query.filter(
                and_(model_mysql_tablesnap.planId == plan_id,
                     # model_mysql_tablesnap.status == 1
                     )).order_by(
                         model_mysql_tablesnap.id.desc()).limit(1).first()
            api_logger.debug("model_mysql_tablesnap数据读取成功")
        except Exception as e:
            api_logger.error("model_mysql_tablesnap数据读取失败,失败原因:" + repr(e))
            return False, None
        else:
            if mysql_snap_data:
                # 如果查询到了,则同步至redis
                redis_set_flag = True
                redis_set_flag = modle_redis_apitestplanworktable.set_table(
                    plan_id, mysql_snap_data.table)
                redis_set_flag = modle_redis_apitestplanworktable.set_time(
                    plan_id)
                if redis_set_flag:
                    return True, mysql_snap_data.table
                else:
                    return False, None
            else:
                # 如果无记录,说明是新测试计划,此时需要在mysql中新增空记录,然后一并同步至redis
                # 新增status为1的snap,内容为空
                new_blank_snap = model_mysql_tablesnap(
                    status=1,
                    planId=plan_id,
                    snapAddTime=datetime.datetime.now(),
                    table="[]")
                try:
                    mysqlpool.session.add(new_blank_snap)
                    mysqlpool.session.commit()
                except Exception as e:
                    api_logger.error("new_blank_snap数据写入失败,失败原因:" + repr(e))
                    return False, None
                else:
                    # 然后再讲空数据同步至redis
                    redis_set_flag = True
                    redis_set_flag = modle_redis_apitestplanworktable.set_table(
                        plan_id, new_blank_snap.table)
                    redis_set_flag = modle_redis_apitestplanworktable.set_time(
                        plan_id)
                    if redis_set_flag:
                        return True, new_blank_snap.table
                    else:
                        return False, None
    # 如果有
    else:
        return True, cache_table_bytes.decode("utf8")
Beispiel #14
0
def plan_worktable_snap_plugin_delete():
    # 初始化返回内容
    response_json = {"code": 200, "msg": "操作成功", "data": {}}

    # 取出
    mail = flask.request.headers['Mail']
    plan_id = int(flask.request.args['plan_id'])
    pid = int(flask.request.args['pid'])

    result, msg = check_plan_owner(mail, plan_id)
    if result is None or result is False:
        return msg

    resource_path = appconfig.get("task", "filePutDir")
    resource_path = resource_path[:-1] if resource_path[
        -1] == "/" else resource_path
    resource_path = "%s/%s/%s" % (resource_path, plan_id, pid)
    if os.path.exists(resource_path) and os.path.isdir(resource_path):
        try:
            shutil.rmtree(resource_path)
        except Exception as e:
            api_logger.error("文件删除失败,失败原因:" + repr(e))
            return route.error_msgs[500]['msg_file_error']

    # 最后返回内容
    return response_json
Beispiel #15
0
def key_projectrole_get():
    # 初始化返回内容
    response_json = {"code": 200, "msg": "数据获取成功", "data": []}

    #查询符合条件的项目id
    try:
        mysql_projectrole_info = model_mysql_roleinfo.query.filter(
            model_mysql_roleinfo.roleIsAdmin == 0,
            model_mysql_roleinfo.roleStatus == 1).all()

    except Exception as e:
        api_logger.error("model_mysql_depository,失败原因:" + repr(e))
        return route.error_msgs[500]['msg_db_error']
    if mysql_projectrole_info is None:
        return route.error_msgs[201]['msg_no_data']
    else:

        for mqit in mysql_projectrole_info:
            response_json["data"].append({
                "id": mqit.roleId,
                "name": mqit.roleName,
                "description": mqit.roleDescription,
            })

    # 最后返回内容
    return response_json
Beispiel #16
0
 def wrapper(*args, **kwargs):
     # 首先检查必传参数Mail/Token
     if 'UserId' not in flask.request.headers or 'Token' not in flask.request.headers:
         return error_msgs[302]['msg_request_params_incomplete']
     user_id = flask.request.headers['UserId']
     user_token = flask.request.headers['Token']
     # 然后检查token是否正确
     # 去缓存的token中查询Mail,不存在的话即为从来没登陆过
     # redis查询无错误信息,不作try处理
     api_logger.debug("准备查询缓存token数据")
     tdata = model_redis_usertoken.query(user_id)
     if tdata is None:
         api_logger.debug("缓存token数据为空")
         return error_msgs[201]['msg_before_login']
     else:
         api_logger.debug("缓存token数据存在")
         # 格式化缓存基础信息内容
         try:
             t = json.loads(tdata.decode("utf8"))
             api_logger.debug("缓存token数据json格式化成功")
         except Exception as e:
             api_logger.error("缓存token数据json格式化失败,失败原因:" + repr(e))
             return error_msgs[500]['msg_json_format_fail']
         # 判断是否一致且有效
         # 判断是否过期
         if user_token != t["userToken"]:
             return error_msgs[401]['msg_token_wrong']
         elif datetime.datetime.strptime(
                 t["validTime"],
                 "%Y-%m-%d %H:%M:%S") < datetime.datetime.now():
             return error_msgs[401]['msg_token_expired']
     # 检查通过,执行应用逻辑
     return func(*args, **kwargs)
Beispiel #17
0
def user_status_put():
    # 初始化返回内容
    response_json = {
        "code": 200,
        "msg": "",
        "data": {}
    }

    # 取出传入参数值
    requestvalue_userid = flask.request.json["user_id"]
    requestvalue_status = flask.request.json["status"]

    # 4.校验所操作的账户是否存在
    # 5.校验所操作的账户所属角色是否是超级管理员
    try:
        ur_data = mysqlpool.session.query(
            model_mysql_userinfo,
            model_mysql_userinfo.userId,
            model_mysql_userinfo.userStatus,
            model_mysql_roleinfo.roleIsAdmin
        ).join(
            model_mysql_roleinfo,
            model_mysql_roleinfo.roleId == model_mysql_userinfo.userRoleId,
            isouter=True
        ).filter(
            model_mysql_userinfo.userId == requestvalue_userid
        ).first()
    except Exception as e:
        logmsg = "数据库中账号数据读取失败,失败原因:" + repr(e)
        api_logger.error(logmsg)
        return route.error_msgs[500]['msg_db_error']
    else:
        if ur_data and ur_data.roleIsAdmin in [0, None]:
            pass
        elif ur_data and ur_data.roleIsAdmin == 1:
            return route.error_msgs[201]['msg_user_is_admin']
        elif ur_data and ur_data.userStatus in [-2, 0]:
            return route.error_msgs[201]['msg_user_cannot_operate']
        else:
            return route.error_msgs[201]['msg_no_user']

    # 6.修改mysql账户状态
    try:
        u_data = model_mysql_userinfo.query.filter(
            model_mysql_userinfo.userId == requestvalue_userid
        ).first()
        logmsg = "数据库中账号数据读取成功"
        api_logger.debug(logmsg)
    except Exception as e:
        logmsg = "数据库中账号数据读取失败,失败原因:" + repr(e)
        api_logger.error(logmsg)
        return route.error_msgs[500]['msg_db_error']
    else:
        u_data.userStatus = requestvalue_status
        mysqlpool.session.commit()

    # 返回成功信息
    response_json["msg"] = "操作成功"
    # 最后返回内容
    return response_json
Beispiel #18
0
def key_catalogues_get():
    # 初始化返回内容
    response_json = {"code": 200, "msg": "数据获取成功", "data": []}

    # 查询基础信息
    try:
        mysql_subjects_info = model_mysql_catalogue.query.filter().all()
    except Exception as e:
        api_logger.error("表model_mysql_subject读取失败,失败原因:" + repr(e))
        return route.error_msgs[500]['msg_db_error']
    else:
        for mpti in mysql_subjects_info:
            response_json["data"].append({
                "id":
                mpti.catalogueId,
                "name":
                mpti.catalogueName,
                "createTime":
                str(mpti.catalogueCreateTime),
                "updateTime":
                str(mpti.catalogueUpdateTime),
            })

    # 最后返回内容
    return response_json
Beispiel #19
0
def role_info_list_get():
    # 初始化返回内容
    response_json = {
        "code": 200,
        "msg": "",
        "data": {
            "total": 0,
            "role_list": {}
        }
    }

    # 取出传入参数值
    page_num = int(flask.request.args['page_num'])
    per_page = int(flask.request.args['per_page'])

    # 查询角色,包括id/name/canmanage
    # 根据角色id,查询角色下关联的账户,判断角色是否可删除
    try:
        rinfo_mysql = mysqlpool.session.query(
            model_mysql_roleinfo, model_mysql_roleinfo.roleId,
            model_mysql_roleinfo.roleName,
            model_mysql_roleinfo.roleIsAdmin).limit(
                # (requestvalue_num - 1) * requestvalue_per,
                per_page).offset((page_num - 1) * per_page).all()
    except Exception as e:
        logmsg = "数据库中角色列表读取失败,失败原因:" + repr(e)
        api_logger.error(logmsg)
        return route.error_msgs[500]['msg_db_error']
    else:
        # 构造role_list
        for r in rinfo_mysql:
            rsome = {
                "id": r.roleId,
                "name": r.roleName,
                "can_manage": True if r.roleIsAdmin == 0 else False
            }
            response_json["data"]["role_list"][r.roleId] = rsome

    try:
        total_mysql = mysqlpool.session.query(
            func.count(
                model_mysql_roleinfo.roleId).label(name="roleNum")).first()
        logmsg = "数据库中角色总数读取成功"
        api_logger.debug(logmsg)
    except Exception as e:
        logmsg = "数据库中角色总数读取失败,失败原因:" + repr(e)
        api_logger.error(logmsg)
        return route.error_msgs[500]['msg_db_error']
    else:
        # 构造total
        response_json["data"]["total"] = total_mysql.roleNum

    # 8.返回成功信息
    response_json["msg"] = "操作成功"
    # 最后返回内容
    return response_json
Beispiel #20
0
def set_snap_table_data(plan_id, table):
    # 从缓存中获取时间
    cache_time_bytes = modle_redis_apitestplanworktable.query_time(
        plan_id=plan_id)
    # 如果时间获取成功,则比较当前时间和缓存的时间
    if cache_time_bytes is not None:
        cache_time = datetime.datetime.strptime(
            cache_time_bytes.decode("utf8"), "%Y-%m-%d %H:%M:%S")
        # 如果没有超出15分钟(可配置),则仅刷新redis中内容
        if (datetime.datetime.now() - cache_time).seconds <= int(
                appconfig.get("task", "snapSyncInterval")):
            modle_redis_apitestplanworktable.set_table(plan_id, table)
            return True
        # 如果超出了15分钟(可配置),则先刷新redis中内容与时间,再同步至mysql生成快照,且更新时间
        else:
            redis_set_flag = True
            redis_set_flag = modle_redis_apitestplanworktable.set_table(
                plan_id, table)
            redis_set_flag = modle_redis_apitestplanworktable.set_time(plan_id)
            if redis_set_flag:
                # mysql中新增snap
                # 将status为1的snap全部置为失效
                try:
                    model_mysql_tablesnap.query.filter(
                        and_(model_mysql_tablesnap.planId == plan_id,
                             model_mysql_tablesnap.status == 1)).update(
                                 {"status": 0})
                    mysqlpool.session.commit()
                except Exception as e:
                    api_logger.error("model_mysql_tablesnap数据更新失败,失败原因:" +
                                     repr(e))
                    return False
                else:
                    # 新增status为1的snap,内容即为接口传参内容
                    new_snap = model_mysql_tablesnap(
                        status=1,
                        planId=plan_id,
                        snapAddTime=datetime.datetime.now(),
                        table=table)
                    try:
                        mysqlpool.session.add(new_snap)
                        mysqlpool.session.commit()
                    except Exception as e:
                        api_logger.error("new_snap数据写入失败,失败原因:" + repr(e))
                        return False
                    else:
                        return True
            else:
                return False
    # 如果时间获取失败,则直接将内容写入redis
    else:
        redis_set_flag = True
        redis_set_flag = modle_redis_apitestplanworktable.set_table(
            plan_id, table)
        redis_set_flag = modle_redis_apitestplanworktable.set_time(plan_id)
        return redis_set_flag
Beispiel #21
0
def role_all_permission_get():
    """
        获取所有角色权限配置清单-api路由
        ----校验
        1.校验传参
        2.校验账户是否存在
        3.校验账户操作令牌
        ----操作
        4.于数据库中查询全量配置清单
    """
    # 初始化返回内容
    response_json = {
        "code": 200,
        "msg": "",
        "data": {
            "permission": {
                "all": {}
            }
        }
    }

    # 4.于数据库中查询全量权限配置清单
    try:
        allp_mysql = model_mysql_functioninfo.query.order_by(
            model_mysql_functioninfo.functionType.asc()).all()
    except Exception as e:
        logmsg = "数据库中角色列表读取失败,失败原因:" + repr(e)
        api_logger.error(logmsg)
        return route.error_msgs[500]['msg_db_error']
    else:
        # 构造角色权限配置清单
        for ap in allp_mysql:
            # 如果此行记录为page,则记录
            if ap.functionType == 1:
                response_json["data"]["permission"]["all"][ap.functionId] = {
                    "id": ap.functionId,
                    "name": ap.functionName,
                    "alias": ap.functionAlias,
                    "description": ap.functionDescription,
                    "component": {}
                }
            else:
                # 如果为组件,则根据rootId判断添加至哪个page的component中
                response_json["data"]["permission"]["all"][
                    ap.rootId]['component'][ap.functionId] = {
                        "id": ap.functionId,
                        "name": ap.functionName,
                        "alias": ap.functionAlias,
                        "description": ap.functionDescription
                    }

    # 5.返回成功信息
    response_json["msg"] = "操作成功"
    # 最后返回内容
    return response_json
Beispiel #22
0
def user_info_get():
    # 初始化返回内容
    response_json = {
        "code": 200,
        "msg": "",
        "data": {
            "user_id": '',
            "nick_name": '',
            "mail_address": '',
            "new_mail_address": '',
            "introduction": '',
            "icon_url": ''
        }
    }

    # 取出传入参数值
    requestvalue_id = flask.request.args["user_id"]

    # 尝试查询mysql
    try:
        uinfo_mysql = mysqlpool.session.query(
            model_mysql_userinfo.userId,
            model_mysql_userinfo.userNickName,
            model_mysql_userinfo.userEmail,
            model_mysql_userinfo.userNewEmail,
            model_mysql_userinfo.userIntroduction,
            model_mysql_userinfo.userHeadIconUrl,
            model_mysql_useroperationrecord.recordId
        ).outerjoin(
            model_mysql_useroperationrecord,
            and_(
                model_mysql_userinfo.userId == model_mysql_useroperationrecord.userId,
                model_mysql_useroperationrecord.recordStatus == 0,
                model_mysql_useroperationrecord.operationId == 3,
                model_mysql_useroperationrecord.recordValidTime > func.now()
            )
        ).filter(
            model_mysql_userinfo.userId == requestvalue_id
        ).first()
    except Exception as e:
        logmsg = "数据库中账户信息读取失败,失败原因:" + repr(e)
        api_logger.error(logmsg)
        return route.error_msgs[500]['msg_db_error']
    else:
        response_json["data"]["user_id"] = uinfo_mysql.userId
        response_json["data"]["nick_name"] = uinfo_mysql.userNickName
        response_json["data"]["mail_address"] = uinfo_mysql.userEmail
        response_json["data"]["new_mail_address"] = uinfo_mysql.userNewEmail if uinfo_mysql.recordId else None
        response_json["data"]["introduction"] = uinfo_mysql.userIntroduction
        response_json["data"]["icon_url"] = uinfo_mysql.userHeadIconUrl

    # 8.返回成功信息
    response_json["msg"] = "操作成功"
    # 最后返回内容
    return response_json
Beispiel #23
0
def key_catalogues_post():
    # 初始化返回内容
    response_json = {"code": 200, "msg": "目录归档成功", "data": None}

    # 取出必传入参
    request_user_id = flask.request.headers['UserId']
    subject_name = flask.request.json['subjectName']
    subject_logo_path = flask.request.json['subjectLogoPath']
    subject_description = flask.request.json['subjectDescription']
    subject_open_level = flask.request.json['subjectOpenLevel']

    # 判断user_id是否存在
    try:
        mysql_userinfo = model_mysql_subject.query.filter(
            model_mysql_subject.userId == request_user_id).first()
        api_logger.debug("账户基础信息读取成功")
    except Exception as e:
        api_logger.error("账户基础信息读取失败,失败原因:" + repr(e))
        return route.error_msgs[500]['msg_db_error']
    else:
        if mysql_userinfo is None:
            return route.error_msgs[201]['msg_no_user']

    # 查询项目名称是否存在
    try:
        mysql_subject = model_mysql_subject.query.filter(
            model_mysql_subject.subjectName == subject_name).first()
    except Exception as e:
        api_logger.error("测试计划类型读取失败,失败原因:" + repr(e))
        return route.error_msgs[500]['msg_db_error']
    else:
        if mysql_subject is None:
            pass
        else:
            return route.error_msgs[201]['msg_exit_subject']
    #获取当前id
    """
        插入项目计划数据

    """
    new_subject_info = model_mysql_subject(
        userId=request_user_id,
        subjectName=subject_name,
        subjectLogoPath=subject_logo_path,
        subjectOpenLevel=subject_open_level,
        subjectDescription=subject_description
        if subject_description else None,
        subjectStatus=1,
    )
    mysqlpool.session.add(new_subject_info)
    mysqlpool.session.commit()

    # 最后返回内容
    return response_json
Beispiel #24
0
def get_single_collection(taskid, plugin_id, skip_num):
    try:
        log_query = mongodb_tasklog_pool['task%s_run' % taskid].find(
            {'id': plugin_id},
            {"_id": 0}
        ).skip(skip_num).limit(1)
    except Exception as e:
        api_logger.error("测试任务:%s运行日志数据读取失败,失败原因:%s" % (taskid, repr(e)))
        return False, None
    else:
        api_logger.debug("测试任务:%s运行日志数据读取成功" % taskid)
        return True, list(log_query)
Beispiel #25
0
def key_caseConflict_get():
    # 初始化返回内容
    response_json = {"code": 200, "msg": "数据获取成功", "data": []}

    # 取出必传入参

    project_id = flask.request.args['projectId']

    # 判断项目是否存在,并且发起了评审,并获取仓库id
    try:
        mysql_project_info = model_mysql_project.query.filter(
            model_mysql_project.id == project_id,
            model_mysql_project.status == 2).first()
    except Exception as e:

        api_logger.error("读取失败,失败原因:" + repr(e))
        return route.error_msgs[500]['msg_db_error']
    else:
        if mysql_project_info is None:
            return response_json

    # 判断项目冲突是否存在
    try:
        mysql_conflict_info = model_mysql_projectArchivePendingCase.query.filter(
            model_mysql_projectArchivePendingCase.projectId == project_id,
            model_mysql_projectArchivePendingCase.status == 1).all()
    except Exception as e:

        api_logger.error("读取失败,失败原因:" + repr(e))
        return route.error_msgs[500]['msg_db_error']
    else:
        if mysql_conflict_info is None:
            return response_json

    # 构造冲突结果返回信息
    for mq in mysql_conflict_info:
        originalCase = []
        projectIdCase = []
        otherCase = []
        originalCase.append(createcase(mq.originalCaseId))
        projectIdCase.append(createcase(mq.projectIdCaseId))
        otherCase.append(createcase(mq.otherCaseId))
        response_json["data"].append({
            "id": mq.id,
            "projectId": project_id,
            "projectName": mysql_project_info.name,
            "originalCase": originalCase,
            "projectIdCase": projectIdCase,
            "otherCase": otherCase,
            "status": mq.status
        })

    return response_json
Beispiel #26
0
def plan_worktable_snap_plugin_file_post():
    # 初始化返回内容
    response_json = {
        "code": 200,
        "msg": "操作成功",
        "data": {
            "name": "",
            "uuid": ""
        }
    }

    # 取出
    mail = flask.request.headers['Mail']
    plan_id = flask.request.form['plan_id']
    pid = flask.request.form['id']

    result, msg = check_plan_owner(mail, plan_id)
    if result is None or result is False:
        return msg

    # 得到uuid转换后的文件名
    request_file = flask.request.files['file']
    response_json['data']['name'] = request_file.filename
    response_json['data']['uuid'] = "%s.%s" % (
        uuid.uuid1().hex, request_file.filename.split('.')[-1])

    # 将文件存储至指定路径下
    # 按照:指定路径/plan_id/id下
    resource_path = appconfig.get("task", "filePutDir")
    resource_path = resource_path[:-1] if resource_path[
        -1] == "/" else resource_path
    resource_path = "%s/%s/%s" % (resource_path, plan_id, pid)

    # 根据配置文件中的路径,判断账户私有文件夹是否存在
    if os.path.exists(resource_path) is False or os.path.isdir(
            resource_path) is False:
        # 新建文件夹
        try:
            os.makedirs(resource_path)
        except Exception as e:
            api_logger.error("文件夹创建失败,失败原因:" + repr(e))
            return route.error_msgs[500]['msg_file_error']
    # 将文件保存至指定路径
    try:
        request_file.save("%s/%s" %
                          (resource_path, response_json['data']['uuid']))
    except Exception as e:
        api_logger.error("文件保存失败,失败原因:" + repr(e))
        return route.error_msgs[500]['msg_file_error']

    # 最后返回内容
    return response_json
Beispiel #27
0
def plan_post():
    # 初始化返回内容
    response_json = {"code": 200, "msg": "操作成功", "data": {}}

    # 取出必传入参
    user_id = flask.request.json['userId']
    plan_type = flask.request.json['planType']
    plan_title = flask.request.json['planTitle']
    open_level = flask.request.json['openLevel']
    plan_description = flask.request.json['planDescription']

    # 判断user_id是否存在
    try:
        mysql_userinfo = model_mysql_userinfo.query.filter(
            model_mysql_userinfo.userId == user_id).first()
        api_logger.debug("账户基础信息读取成功")
    except Exception as e:
        api_logger.error("账户基础信息读取失败,失败原因:" + repr(e))
        return route.error_msgs[500]['msg_db_error']
    else:
        if mysql_userinfo is None:
            return route.error_msgs[201]['msg_no_user']

    # 查询测试计划类型是否存在
    try:
        mysql_plantype = model_mysql_plantype.query.filter(
            model_mysql_plantype.typeId == plan_type).first()
    except Exception as e:
        api_logger.error("测试计划类型读取失败,失败原因:" + repr(e))
        return route.error_msgs[500]['msg_db_error']
    else:
        if mysql_plantype is None:
            return route.error_msgs[201]['msg_no_plan_type']
    """
        插入测试计划数据
        关于测试计划所有者类型:
        0 个人
        1 团队
    """
    new_plan_info = model_mysql_planinfo(
        ownerId=user_id,
        planType=plan_type,
        planTitle=plan_title,
        planDescription=plan_description if plan_description else None,
        planOpenLevel=open_level,
        planOwnerType=0)
    mysqlpool.session.add(new_plan_info)
    mysqlpool.session.commit()

    # 最后返回内容
    return response_json
Beispiel #28
0
def key_subject_get():
    # 初始化返回内容
    response_json = {
        "code": 200,
        "msg": "数据获取成功",
        "data": {
            "id": 0,
            "name": None,
            "logoPath": None,
            "description": None,
            "status": 1
        }
    }

    subject_user_id = None
    # 取出入参
    request_user_id = flask.request.headers['UserId']
    subject_id = flask.request.args['subjectId']

    # 查询项目基础信息,并取出所属者账户id
    try:
        mysql_subject_info = model_mysql_subject.query.filter(
            model_mysql_subject.subjectId == subject_id).first()
    except Exception as e:
        api_logger.error("model_mysql_subjectinfo数据读取失败,失败原因:" + repr(e))
        return route.error_msgs[500]['msg_db_error']
    else:
        if mysql_subject_info is None:
            return route.error_msgs[201]['msg_no_subject']
        else:
            subject_user_id = mysql_subject_info.userId
            response_json['data']['id'] = mysql_subject_info.subjectId
            response_json['data']['name'] = mysql_subject_info.subjectName
            response_json['data'][
                'logoPath'] = mysql_subject_info.subjectLogoPath
            response_json['data'][
                'description'] = mysql_subject_info.subjectDescription
            response_json['data']['status'] = mysql_subject_info.subjectStatus

    # 根据项目状态以及操作者id/计划拥有者id判断返回内容
    if request_user_id == subject_user_id:
        pass
    else:
        if mysql_subject_info.subjectStatus in (1, 2):
            pass
        else:
            return route.error_msgs[201]['msg_no_subject']

    # 最后返回内容
    return response_json
Beispiel #29
0
def key_projectlist_get():
    # 初始化返回内容
    response_json = {
        "code": 200,
        "msg": "数据获取成功",
        "data": []
    }

    project_id = flask.request.args['id']

    # 查询符合条件的项目并获得仓库id
    try:
        mysql_project_info = model_mysql_project.query.filter(
            model_mysql_project.id == project_id,
            model_mysql_project.status != -1
        ).first()
    except Exception as e:
        api_logger.error("model_mysql_depository,失败原因:" + repr(e))
        return route.error_msgs[500]['msg_db_error']
    if mysql_project_info is None:
        print(111)
        return route.error_msgs[201]['msg_no_project']
    else:
        depository_Id = mysql_project_info.depositoryId

    # 查询符合条件的项目
    try:
        mysql_projects_info = model_mysql_project.query.filter(
            model_mysql_project.depositoryId == depository_Id,
            model_mysql_project.status != -1,
            model_mysql_project.id != project_id
        ).all()
    except Exception as e:
        api_logger.error("model_mysql_depository,失败原因:" + repr(e))
        return route.error_msgs[500]['msg_db_error']
    if mysql_projects_info is None:
        print(2222)
        return route.error_msgs[201]['msg_no_project']
    else:
        for mqti in mysql_projects_info:
            response_json["data"].append({
                "id":mqti.id,
                "name":mqti.name,
                "decription":mqti.description,
                "coverOssPath":mqti.coverOssPath
            })

    # 最后返回内容
    return response_json
Beispiel #30
0
def key_catalogue_get():
    # 初始化返回内容
    response_json = {
        "code": 200,
        "msg": "数据获取成功",
        "data": {
            "catalogueId": 1,
            "catalogueName": None,
            "createTime": None,
            "updateTime": None
        }
    }

    # 取出入参

    catalogue_id = flask.request.args['catalogueId']
    subject_id = flask.request.args['subjectId']

    # 查询项目基础信息,并取出所属者账户id
    try:
        mysql_catalogue_info = model_mysql_catalogue.query.filter(
            model_mysql_catalogue.catalogueId == catalogue_id).first()

    except Exception as e:
        api_logger.error("model_mysql_subjectinfo数据读取失败,失败原因:" + repr(e))
        return route.error_msgs[500]['msg_db_error']
    if mysql_catalogue_info is None:
        return route.error_msgs[201]['msg_no_catalogue']
    elif mysql_catalogue_info.subjectId != int(subject_id):
        return route.error_msgs[201]['msg_data_error']
    else:
        response_json['data']['catalogueId'] = mysql_catalogue_info.catalogueId
        response_json['data'][
            'catalogueName'] = mysql_catalogue_info.catalogueName
        response_json['data']['createTime'] = str(
            mysql_catalogue_info.catalogueCreateTime)
        response_json['data']['updateTime'] = str(
            mysql_catalogue_info.catalogueUpdateTime)

    # 根据项目状态以及操作者id/计划拥有者id判断返回内容

    if mysql_catalogue_info.catalogueStatus in (1, 2):
        pass
    else:
        return route.error_msgs[201]['msg_no_catalogue']

    # 最后返回内容
    return response_json