コード例 #1
0
def update_channel():
    """更新通道"""
    if not request.content_type == 'application/json':
        return render_response(-1,msg="Content-type must be application/json.")

    form = ChannelForm.from_json(request.json)
    channel_id = request.json.get('channel_id')

    if not form.validate() or not is_uuid(channel_id):
        msg = "parameter error:{}".format(form.errors)
        logger.warning(msg)
        return render_response(-1, msg=msg)

    channel = Channel.query.get(channel_id)
    if not channel:
        msg = "channel_id: {} is not exist".format(channel_id)
        logger.error(msg)
        return render_response(-1, msg=msg)

    channel.camera_id = form.camera_id.data
    channel.channel_name = form.channel_name.data
    channel.channel_number = form.channel_number.data
    channel.gb_number = form.gb_number.data
    channel.yun_tai = form.yun_tai.data
    channel.status = form.status.data
    try:
        channel.update()
    except Exception as e:
        logger.error()
        return render_response(-1, msg='datebase error')
    return render_response(0)
コード例 #2
0
def get_all_organizations():
    """
    Get all the organizations for the front end to display the tree structure
    获取所有组织机构,供前端展示树状结构
    :return:
    """
    all_info = []
    try:
        organizations = Organization.query.filter_by(is_delete=False).all()

        for org in organizations:
            org_info = {
                "organization_id": org.id,
                "organization_name": org.organization_name,
                "parent_id": org.parent_id
            }
            all_info.append(org_info)
        code = 0
        msg = "查询成功"
    except Exception as e:
        logger.error(e)
        code = -1
        msg = "查询失败"
    return response_tem(
        code=code,
        msg=msg,
        data=all_info
    )
コード例 #3
0
    def start_call_api(self):
        # 从redis中获取data 调用api
        logger.info("启动redis 任务监听进程。")
        while True:
            ret = redis_store.brpop(["task_high", "task_middle", "task_low"])
            data = ret[1]
            logger.info("从redis中获取视频诊断任务: {}.".format(data))
            try:
                res = self.call_api(data)  # 调用api
            except Exception as e:
                # print("****", e)
                logger.critical("视频诊断接口调用错误: {}".format(e))
                continue

            if res['code'] == 1:  # api调用成功
                # print("***** success")
                logger.info("视频诊断接口调用成功:{}".format(data))
                pass

            elif res["code"] == -10000:  # 失败:线程饱和
                logger.warning("视频诊断服务,线程饱和。")
                while True:
                    time.sleep(1)
                    res = self.call_api(data)
                    if res['code'] == 1:
                        break
            else:
                # print("video diagnosis api call error, code: {}".format(res["code"]))
                logger.error("视频诊断接口调用失败,错误码:{}, data:{}".format(
                    res["code"], data))
コード例 #4
0
ファイル: modify_config.py プロジェクト: ccevan/deploy
def ums_config(path, database_ip, database_password, application_ip):
    """

    :param path: 配置文件路径
    :param database_ip: 数据库ip,字符串格式
    :param database_passwd: 数据库密码,字符串格式
    :param application_ip: 应用服务器IP,字符串格式
    :return: 成功返回True
             失败返回False
    """
    try:
        with open(path, "rb+") as f:
            # 解析json
            json_info = demjson.decode(f.read(), encoding="utf-8")

            # 替换需要替换的部分
            server = "Server=" + database_ip + ";Database=UMSCore-SPZL;UID=sa;PWD=" + database_password
            json_info["ConnectionStrings"]["DefaultConnection"] = server
            deploy_url = "http://" + application_ip + ":5556"
            json_info["appSettings"]["DeployUrl"] = deploy_url

            # 转为json字符串形式
            json_str = demjson.encode(
                json_info
            )  # .replace(",", ",\n").replace("{", "\n{\n").replace("}", "\n}\n")
        with open(path, "w", encoding="utf-8") as f:
            f.write(json_str)
        return True
    except BaseException as e:
        logger.error(e)
        return False
コード例 #5
0
def files():
    """
    查询已上传文件的信息, 包括文件名 文件大小, 文件类型 , 最后更新时间
    :return:
    """
    json_data = return_json(request)
    page = json_data.get("page", None)
    page_size = json_data.get("page_size", 10)
    if not (page and page_size):
        code = -1
        msg = "page和page_size参数必填"
        return response_tem(code=code, msg=msg)

    if type(page) is str:
        if not page.isdigit():
            code = -1
            msg = "page应该是数字类型"
            return response_tem(code=code, msg=msg)

    if type(page_size) is str:
        if not page_size.isdigit():
            code = -1
            msg = "page_size应该是数字类型"
            return response_tem(code=code, msg=msg)
    page = int(page)
    page_size = int(page_size)

    all_info = []
    try:
        search_param = {"is_delete": False}
        pagination = File.query.filter_by(**search_param).paginate(
            page, page_size, 0)
        all_data = pagination.total
        all_page = pagination.pages
        now_page = pagination.page
        all_file = pagination.items
        for info in all_file:
            file_info = {
                "file_id": info.id,
                "name": info.name,
                "type": info.type,
                "size": info.size,
                "update_time": info.update_time
            }
            all_info.append(file_info)
        code = 0
        msg = "查询成功"
    except Exception as e:
        logger.error(e)
        code = -1
        msg = "查询失败"
        all_data = None
        all_page = None
        now_page = None
    return response_tem(code=code,
                        data=all_info,
                        msg=msg,
                        all_data=all_data,
                        all_page=all_page,
                        page=now_page)
コード例 #6
0
def search_camera_groups():
    logger.info("收到查询摄像机分组树命令")
    try:
        task_info = get_json(request)
        logger.info("收到的json是:{}".format(str(task_info)))
        userdata = task_info["userdata"]
        logger.info(userdata)
    except BaseException as e:
        # json格式错误
        logger.error(e)
        return get_res(-1, userdata)
    data_list = list()
    ret = dict()
    # 对camera_group表进行查询
    try:
        groupinfo_list = CameraGroup.query.filter(
            CameraGroup.is_delete == False).all()
        for groupinfo in groupinfo_list:
            group_dict = dict()
            group_dict["group_id"] = groupinfo.id
            group_dict["group_name"] = groupinfo.group_name
            group_dict["parent_id"] = groupinfo.parent_id
            data_list.append(group_dict)
    except BaseException as e:
        # 接口调用失败
        logger.error(e)
        return get_res(-1, userdata)
    ret["code"] = 0
    ret["data"] = data_list
    ret["userdata"] = userdata
    logger.debug("返回的json是:{}".format(ret))
    return jsonify(ret)
コード例 #7
0
ファイル: ServerApi.py プロジェクト: ccevan/deploy
def delete_server():
    """
    根据id删除某个server
    :return:
    """
    json_data = return_json(request)
    server_id = json_data.get("server_id", None)
    if not server_id:
        code = -1
        msg = "server_id is required"
        return response_tem(code=code, msg=msg)
    try:
        search_param = {"is_delete": False, "id": server_id}
        server_info = Server.query.filter_by(**search_param).first()
        if not server_info:
            code = -1
            msg = "没找到该server, 可能已经删除"
            return response_tem(code=code, msg=msg)
        server_info.is_delete = True
        db.session.add(server_info)
        db.session.commit()
        code = 0
        msg = "删除成功"
    except Exception as e:
        logger.error(e)
        code = -1
        msg = "删除失败"
    return response_tem(code=code, msg=msg)
コード例 #8
0
ファイル: ServerApi.py プロジェクト: ccevan/deploy
def search_server():
    """
    根据服务id查询相关信息,用于修改server信息回显
    :return:
    """
    json_data = return_json(request)
    server_id = json_data.get("server_id", None)
    if not server_id:
        code = -1
        msg = "server_id is required"
        return response_tem(code=code, msg=msg)
    try:
        search_param = {"is_delete": False, "id": server_id}
        data = Server.query.filter_by(**search_param).first()
        if not data:
            code = -1
            msg = "没有找到该server"
            return response_tem(code=code, msg=msg)
        info = {
            "name": data.name,
            "ip": data.ip,
            "port": data.port,
            "user_name": data.user_name,
            "user_password": data.user_password
        }
        code = 0
        msg = "查询成功"
    except Exception as e:
        logger.error(e)
        code = -1
        msg = "查询失败"
        info = None
    return response_tem(code, data=info, msg=msg)
コード例 #9
0
def add_camera_list():
    logger.info("收到分组下添加摄像机命令")
    try:
        task_info = get_json(request)
        logger.info("收到的json是:{}".format(str(task_info)))
        group_id = task_info["group_id"]
        camera_list = task_info["camera_list"]
        userdata = task_info["userdata"]
        logger.info((group_id, camera_list, userdata))
    except BaseException as e:
        # json格式错误
        logger.error(e)
        return get_res(-1, userdata)

    try:
        for camera_id in camera_list:
            camerainfo = Camera.query.filter(
                and_(Camera.id == camera_id, Camera.is_delete == False)).first()
            camerainfo.cameragroup_id = group_id
            db.session.add(camerainfo)
        db.session.commit()
    except BaseException as e:
        # 接口调用失败
        logger.error(e)
        db.session.rollback()
        return get_res(-1, userdata)
    logger.info("分组下添加摄像机成功")
    return get_res(0, userdata)
コード例 #10
0
def show_num_rate():
    """
    Demonstrate the number of failures and failure rates of the camera
    展示摄像机的故障数和故障率
    :return:
    """
    all_info = []
    try:
        fault_data = FaultCount.query.filter(
            FaultCount.organization_id == None,
            FaultCount.cameraplatform_id == None).all()
        for fault in fault_data:
            fault_list = []

            date = fault.date
            num = fault.num
            rate = fault.rate
            fault_list.append(date)
            fault_list.append(num)
            fault_list.append(rate)
            all_info.append(fault_list)

        code = 0
        msg = "查询成功"

    except Exception as e:
        db.session.rollback()
        logger.error(e)
        code = -1
        msg = "查询失败"
    return response_tem(code=code, msg=msg, data=all_info)
コード例 #11
0
def search_camera_list():
    logger.info("收到查询分组下摄像机列表命令")
    data_list = list()
    ret = dict()
    try:
        task_info = get_json(request)
        logger.info("收到的json是:{}".format(str(task_info)))
        group_id = task_info["group_id"]
        userdata = task_info["userdata"]
        logger.info((group_id, userdata))
    except BaseException as e:
        # json格式错误
        logger.error(e)
        return get_res(-1, userdata)
    # 对camera表进行查询
    try:
        camerainfo_list = Camera.query.filter(
            and_(Camera.cameragroup_id == group_id, Camera.is_delete == False)).all()
        for camerainfo in camerainfo_list:
            camera_dict = dict()
            camera_dict["camera_id"] = camerainfo.id
            camera_dict["camera_name"] = camerainfo.camera_name
            data_list.append(camera_dict)
    except BaseException as e:
        # 接口调用失败
        logger.error(e)
        return get_res(-1, userdata)
    ret["code"] = 0
    ret["data"] = data_list
    ret["userdata"] = userdata
    logger.debug("返回的json是:{}".format(ret))
    return jsonify(ret)
コード例 #12
0
ファイル: modify_config.py プロジェクト: ccevan/deploy
def spzlweb_config(path, application_ip, stream_ip):
    """

    :param path: 配置文件路径
    :param application_ip: 应用服务器IP,字符串格式
    :param stream_ip: 流媒体服务器IP,字符串格式
    :return: 成功返回True
             失败返回False
    """
    try:
        with open(path, "rb+") as f:
            json_info = demjson.decode(f.read(), encoding="utf-8")

            server_url = "http://" + application_ip + ":8088"
            json_info["serviceUrl"] = server_url

            ums_url = "http://" + application_ip + ":5556"
            json_info["umsUrl"] = ums_url

            stream_url = "http://" + stream_ip + ":8080"
            json_info["streamUrl"] = stream_url

            web_site_address = "http://" + application_ip + ":8087"
            json_info["webSiteAddress"] = web_site_address

            json_str = demjson.encode(
                json_info
            )  # .replace(",", ",\n").replace("{", "\n{\n").replace("}", "\n}\n")
        with open(path, "w", encoding="utf-8") as f:
            f.write(json_str)
        return True
    except BaseException as e:
        logger.error(e)
        return False
コード例 #13
0
def accurate_query():
    """
    accurate query the organization's information
    精确查询组织机构信息,验证该组织机构名称是否存在
    :return:
    """
    json_data = return_json(request)
    organization_name = json_data.get("organization_name", None)
    user_data = json_data.get("userdata", None)
    data = None
    try:
        if not organization_name:
            code = -1
            msg = "参数错误"
            return response_tem(code=code, msg=msg, userdata=user_data, data=data)
        org = Organization.query.filter_by(organization_name=organization_name).first()
        code = 0

        if not org:
            data = 0
            msg = "该组织机构暂未添加"
        else:
            data = -1
            msg = "该组织机构已存在"
    except Exception as e:
        logger.error(e)
        code = -1
        msg = "查询失败"
        data = None
    return response_tem(
        code=code,
        msg=msg,
        data=data,
        userdata=user_data
    )
コード例 #14
0
ファイル: ServiceApi.py プロジェクト: ccevan/deploy
def project():
    """
    查询所有项目信息
    :return:
    """
    json_data = return_json(request)
    page = json_data.get("page", None)
    page_size = json_data.get("page_size", 10)

    if not (page and page_size):
        code = -1
        msg = "page和page_size参数必填"
        return response_tem(code=code, msg=msg)

    if type(page) is str:
        if not page.isdigit():
            code = -1
            msg = "page应该是数字类型"
            return response_tem(code=code, msg=msg)

    if type(page_size) is str:
        if not page_size.isdigit():
            code = -1
            msg = "page_size应该是数字类型"
            return response_tem(code=code, msg=msg)
    page = int(page)
    page_size = int(page_size)

    all_info = []
    try:
        search_param = {"is_delete": False}
        pagination = Project.query.filter_by(**search_param).paginate(
            page, page_size, 0)
        all_data = pagination.total
        all_page = pagination.pages
        now_page = pagination.page
        all_proj = pagination.items
        for proj in all_proj:
            proj_info = {
                "id": proj.id,
                "project_name": proj.project_name,
                "update_time": proj.update_time
            }
            all_info.append(proj_info)
        code = 0
        msg = "查询成功"
    except Exception as e:
        logger.error(e)
        code = -1
        msg = "查询失败"
        all_data = None
        all_page = None
        now_page = None
    return response_tem(code=code,
                        msg=msg,
                        data=all_info,
                        all_data=all_data,
                        all_page=all_page,
                        page=now_page)
コード例 #15
0
ファイル: modify_config.py プロジェクト: ccevan/deploy
def spzlapi_config(path, database_ip, database_password, application_ip,
                   stream_ip):
    """
    修改视频智联api服务的配置文件
    :param path: 配置文件绝对路径
    :param database_ip: 数据库ip
    :param database_password: 数据库密码
    :param application_ip: 应用服务器ip
    :param stream_ip: 流媒体服务器ip
    :return:
    """
    try:
        with open(path, 'r') as f_read:
            json_data = demjson.decode(f_read.read())

            DefaultConn = json_data["ConnectionStrings"]["DefaultConnection"]
            if DefaultConn:
                DefaultConn = "Server=" + database_ip + ";Database=VideoManagement;UID=sa;PWD=" + database_password
                json_data["ConnectionStrings"][
                    "DefaultConnection"] = DefaultConn  # 修改后的DefaultConnection
            else:
                return False

            UmsConn = json_data["UmsConnection"]
            if UmsConn:
                UmsConn = "Server=" + database_ip + ";Database=UmsCore-SPZL;UID=sa;PWD=" + database_password
                json_data["UmsConnection"] = UmsConn  # 修改后的UmsConnection
            else:
                return False

            RunPath = json_data["RunPath"]
            if RunPath:
                RunPath = "http://" + application_ip + ":8088"
                json_data["RunPath"] = RunPath
            else:
                return False
            StreamUrl = json_data["StreamUrl"]
            if StreamUrl:
                StreamUrl = "http://" + stream_ip + ":8080"
                json_data["StreamUrl"] = StreamUrl
            else:
                return False
            PVGAddress = json_data["PVGAddress"]
            if PVGAddress:
                PVGAddress = "http://" + database_ip + ":503"
                json_data["PVGAddress"] = PVGAddress
            else:
                return False
            redislinkAddress = json_data["redislinkAddress"]
            if redislinkAddress:
                redislinkAddress = application_ip + ":6379"
                json_data["redislinkAddress"] = redislinkAddress
            with open(path, "w") as f_write:
                f_write.write(demjson.encode(json_data))
        return True
    except Exception as e:
        logger.error(e)
        return False
コード例 #16
0
ファイル: ServerApi.py プロジェクト: ccevan/deploy
def modify_server():
    """
    根据server_id修改server信息
    :return:
    """
    json_data = return_json(request)
    server_id = json_data.get("server_id", None)
    name = json_data.get("name", None)
    ip = json_data.get("ip", None)
    port = json_data.get("port", None)
    user_name = json_data.get("user_name", None)
    user_password = json_data.get("user_password", None)
    if not server_id:
        code = -1
        msg = "server_id is required"
        return response_tem(code=code, msg=msg)
    param_list = [name, ip, port, user_name, user_password]
    for param in param_list:
        if not param:
            code = -1
            msg = "all param is required"
            return response_tem(code=code, msg=msg)
    search_param = {"is_delete": False, "id": server_id}
    try:

        server_info = Server.query.filter_by(**search_param).first()
        if server_info.name != name:
            param = {"is_delete": False, "name": name}
            server_list = Server.query.filter_by(**param).all()
            if len(server_list):
                code = -1
                msg = "该名称已存在"
                return response_tem(code=code, msg=msg)
        if server_info.ip != ip:
            param = {"is_delete": False, "ip": ip}
            server_list = Server.query.filter_by(**param).all()
            if len(server_list):
                code = -1
                msg = "该ip已存在"
                return response_tem(code=code, msg=msg)

        server_info.name = name
        server_info.ip = ip
        server_info.port = port
        server_info.user_name = user_name
        server_info.user_password = user_password
        db.session.add(server_info)
        db.session.commit()
        code = 0
        msg = "修改成功"
    except Exception as e:
        logger.error(e)
        code = -1
        msg = "修改失败"
    return response_tem(code=code, msg=msg)
コード例 #17
0
def auto_statistic_fault():
    url = 'http://127.0.0.1:8000/api/v1/task/tableCount'
    params = json.dumps({}).encode('utf8')
    req = urllib.request.Request(url,
                                 data=params,
                                 headers={'content-type': 'application/json'})
    response = urllib.request.urlopen(req)
    res = response.read().decode()
    res = json.loads(res)
    if res['code'] != 0:
        logger.error("自动统计故障识别")
コード例 #18
0
def find_son_node():
    """
    Find son organization
    查找子级机构
    :return:
    """

    json_data = return_json(request)
    o_id = json_data.get("organization_id", None)
    user_data = json_data.get("userdata", None)

    if not o_id or type(o_id) is not str or not len(o_id) == 32:
        code = -1
        msg = "参数错误"
        return response_tem(
            code=code,
            msg=msg,
            userdata=user_data
        )

    all_info = []

    try:
        organization = Organization.query.filter_by(id=o_id, is_delete=False).first()

        if not organization:
            code = -1
            msg = "该组织机构不存在或已被删除"
            return response_tem(
                code=code,
                msg=msg,
                userdata=user_data
            )

        for org in organization.child:

            org_info = {
                "organization_id": org.id,
                "organization_name": org.organization_name
            }
            all_info.append(org_info)
        code = 0
        msg = "查找成功"
    except Exception as e:
        logger.error(e)
        code = -1
        msg = "查找失败"
    return response_tem(
        code=code,
        msg=msg,
        data=all_info,
        userdata=user_data
    )
コード例 #19
0
def AddUser():
    try:
        user = User(name='changhao1',
                    password='******',
                    email='*****@*****.**')
        db.session.add(user)
        db.session.commit()
    except Exception as e:
        logger.error(e)
        db.session.rollback()
        return 'add failed'
    else:
        return 'add ok!!!'
コード例 #20
0
ファイル: ServerApi.py プロジェクト: ccevan/deploy
def add_server():
    """
    add server
    :return:
    """
    json_data = return_json(request)
    name = json_data.get("name", None)
    ip = json_data.get("ip", None)
    port = json_data.get("port", None)
    user_name = json_data.get("user_name", None)
    user_password = json_data.get("user_password", None)

    param_list = [name, ip, port, user_name, user_password]
    for param in param_list:
        if param is None:
            code = -1
            msg = "all param is required"
            return response_tem(code=code, msg=msg)
    try:
        param = {"is_delete": False, "name": name}
        server_list = Server.query.filter_by(**param).all()
        if len(server_list):
            code = -1
            msg = "该名称已存在"
            return response_tem(code=code, msg=msg)

        param = {"is_delete": False, "ip": ip}
        server_list = Server.query.filter_by(**param).all()
        if len(server_list):
            code = -1
            msg = "该ip已存在"
            return response_tem(code=code, msg=msg)

        server_param = {
            "name": name,
            "ip": ip,
            "port": str(port),
            "user_name": user_name,
            "user_password": user_password
        }
        new_server = Server(**server_param)
        db.session.add(new_server)
        db.session.commit()
        code = 0
        msg = "添加成功"

    except Exception as e:
        logger.error(e)
        code = -1
        msg = "添加失败"
    return response_tem(code=code, msg=msg)
コード例 #21
0
def fault_count():
    """
    Query the fault type and the number of faults at the current time
    查询当前时刻的故障种类及故障数量
    :return:
    """

    all_info = []

    try:
        video_data = Fault.query.join(Camera).filter(
            Fault.type1 == True, Camera.is_delete == False).all()
        network_data = Fault.query.join(Camera).filter(
            Fault.type2 == True, Camera.is_delete == False).all()
        time_data = Fault.query.join(Camera).filter(
            Fault.type3 == True, Camera.is_delete == False).all()

        video_num = len(video_data)
        network_num = len(network_data)
        time_num = len(time_data)
        data_info = {
            "video_num": video_num,
            "network_num": network_num,
            "time_num": time_num
        }

        total_camera = TaskCameraRelationship.query.group_by(
            TaskCameraRelationship.camera_id).all()
        total_camera = [
            rel for rel in total_camera if not rel.camera.is_delete
        ]
        total_camera_num = len(total_camera)
        fault_camera = Fault.query.filter(Fault.status == 0).group_by(
            Fault.camera_id).all()
        fault_camera = [
            cam for cam in fault_camera if not cam.camera.is_delete
        ]
        fault_camera_num = len(fault_camera)
        normal_camera_num = total_camera_num - fault_camera_num
        data_info["normal_num"] = normal_camera_num
        all_info.append(data_info)

        code = 0
        msg = "查询成功"

    except Exception as e:
        logger.error(e)
        code = -1
        msg = "查询失败"

    return response_tem(code=code, data=all_info, msg=msg)
コード例 #22
0
def get_platforms_by_organization():
    """
    Get platform information based on organization
    根据组织机构获取平台信息
    :return:
    """
    json_data = return_json(request)
    o_id = json_data.get("id", None)
    user_data = json_data.get("userdata", None)

    if not o_id or type(o_id) is not str or not len(o_id) == 32:
        code = -1
        msg = "参数错误"
        return response_tem(
            code=code,
            msg=msg,
            userdata=user_data
        )

    all_info = []

    try:
        organization = Organization.query.filter_by(id=o_id, is_delete=False).first()
        if not organization:
            code = -1
            msg = "id:{}不存在或已被删除".format(o_id)
            logger.error(msg)
            return response_tem(code=code, msg=msg, userdata=user_data)
        platforms = CameraPlatform.query.filter_by(is_delete=False, organization=organization).all()
        all_data = len(platforms)
        for platform in platforms:
            platform_info = {
                "platform_id": platform.id,
                "camera_platform_name": platform.camera_platform_name
            }
            all_info.append(platform_info)
        code = 0
        msg = "查询成功"
    except Exception as e:
        code = -1
        msg = "查询失败"
        all_data = None
        logger.error(e)
    return response_tem(
        code=code,
        msg=msg,
        data=all_info,
        all_data=all_data,
        userdata=user_data
    )
コード例 #23
0
def add_organization():
    """
    Add organization information
    添加组织机构信息, post
    :return:
    """
    json_data = return_json(request)
    organization_name = json_data.get("organization_name", None)
    organization_number = json_data.get("organization_number", None)
    organization_desc = json_data.get("organization_desc", None)
    parent_id = json_data.get("parent_id", None)
    userdata = json_data.get("userdata", None)

    if parent_id and (not len(parent_id) == 32):
        code = -1
        msg = "父级组织机构id长度应为32"
        return response_tem(code=code, msg=msg, userdata=userdata)

    if not (organization_name and organization_number):
        code = -1
        msg = "组织机构名称和编号必填"
        return response_tem(code=code, msg=msg, userdata=userdata)

    try:
        if parent_id:
            parent = Organization.query.filter_by(is_delete=False, id=parent_id).first()
            if not parent:
                code = -1
                msg = "父级id不存在"
                return response_tem(code=code, msg=msg, userdata=userdata)

        param = {
            "organization_name": organization_name,
            "organization_number": organization_number,
            "organization_desc": organization_desc,
            "parent_id": parent_id if parent_id else None
        }
        organization = Organization(**param)
        db.session.add(organization)
        db.session.commit()
        code = 0
        msg = "添加成功"
    except Exception as e:
        db.session.rollback()
        logger.error(e)
        code = -1
        msg = "添加失败"
    return response_tem(code=code, msg=msg, userdata=userdata)
コード例 #24
0
def delete_platform():
    """
    Delete platform information based on platform id
    根据平台id删除平台信息
    :return:
    """
    json_data = return_json(request)
    ids = json_data.get("ids", None)
    user_data = json_data.get("userdata", None)
    if (type(ids) is str and not len(ids) == 32) or \
            ids is None or len(ids) == 0:
        code = -1
        msg = "ids格式非法"
        return response_tem(code=code, msg=msg, userdata=user_data)
    if type(ids) is list:
        for _id in ids:
            if not len(_id) == 32:
                code = -1
                msg = "ids格式非法"
                return response_tem(code=code, msg=msg, userdata=user_data)
    if type(ids) is str and len(ids) == 32:
        ids = [ids]
    try:
        for _id in ids:

            platform = CameraPlatform.query.filter_by(id=_id,
                                                      is_delete=False).first()
            if not platform:
                code = -1
                msg = "id:{}不存在或已被删除".format(_id)
                logger.error(msg)
                return response_tem(code=code, msg=msg, userdata=user_data)
            for camera in platform.cameras.all():
                camera.is_delete = True
                db.session.add(camera)
            platform.is_delete = True
            db.session.add(platform)
        db.session.commit()

        code = 0
        msg = "删除平台信息成功"
    except Exception as e:
        db.session.rollback()

        code = -1
        msg = "删除平台信息失败"
        logger.error(e)
    return response_tem(code=code, msg=msg, userdata=user_data)
コード例 #25
0
def get_organization_by_id():
    """
    Query organization information based on id
    根据id查询组织机构信息, post
    :return:
    """
    json_data = return_json(request)
    o_id = json_data.get("organization_id", None)
    user_data = json_data.get("userdata", None)

    if o_id is None:
        code = -1
        msg = "没有获取到需要查询的id"
        return response_tem(
            code=code,
            msg=msg,
            userdata=user_data
        )

    all_info = []

    try:
        organization = Organization.query.filter_by(id=o_id, is_delete=False).first()
        organization_info = {
            "organization_name": organization.organization_name,
            "organization_number": organization.organization_number,
            "organization_desc": organization.organization_desc,
            "parent_id": organization.parent_id if organization.parent_id else None,
            "parent_organization_name": organization.parent.organization_name if organization.parent_id else None,
            "create_time": organization.create_time,
            "update_time": organization.update_time
        }
        all_info.append(organization_info)

        code = 0
        msg = "查询成功"
    except Exception as e:
        logger.error(e)
        code = -1
        msg = "查询失败"
    return response_tem(
        code=code,
        msg=msg,
        data=all_info,
        userdata=user_data
    )
コード例 #26
0
def delete_task():
    """根据id删除任务"""
    if not request.content_type == 'application/json':
        return render_response(-1,
                               msg="Content-type must be application/json.")

    task_info = request.json
    task_ids = task_info.get("task_id")
    if not task_ids:
        return render_response(-1, msg="task_id is required.")

    userdata = task_info.get("userdata")
    logger.info((task_ids, userdata))

    if isinstance(task_ids, str):
        task_ids = [task_ids]

    # 对task_id进行查询
    try:
        for task_id in task_ids:
            taskinfo = Task.query.filter((Task.id == task_id)
                                         & (Task.is_delete == False)).first()
            if taskinfo is None:
                logger.error("task not exist.")
                return render_response(-1,
                                       userdata=userdata,
                                       msg='task not exist.')
            taskinfo.is_delete = True
            db.session.add(taskinfo)

            # 删除调度器中的任务
            try:
                scheduler.remove_job(task_id)
            except:
                pass

        db.session.commit()

    except Exception as e:
        # 接口调用失败
        logger.error("task delete error:{}".format(e))
        db.session.rollback()
        msg = "database delete error."
        return render_response(-1, msg=msg, userdata=userdata)
    # logger.info("删除任务成功")
    return render_response(0, userdata=userdata, msg="delete success.")
コード例 #27
0
def dimsearch_camera_list():
    logger.info("摄像头名称模糊查询命令")
    data_list = list()
    ret = dict()
    try:
        task_info = get_json(request)
        logger.info("收到的json是:{}".format(str(task_info)))
        pagesize = task_info["pagesize"]
        pagenum = task_info["pagenum"]
        keyword = task_info["keyword"]
        userdata = task_info["userdata"]
        logger.info((pagesize, pagenum, keyword, userdata))
    except BaseException as e:
        # json格式错误
        logger.error(e)
        return get_res(-1, userdata)
    try:
        if keyword:
            # 对camera表进行查询
            pagination = Camera.query.filter(
                and_(Camera.camera_name.like("%" + keyword + "%"),
                     Camera.cameragroup_id == None,Camera.is_delete == False)).paginate(
                pagenum, per_page=pagesize, error_out=False)
        else:
            pagination = Camera.query.filter(
                and_(Camera.cameragroup_id == None, Camera.is_delete == False)).paginate(
                pagenum, per_page=pagesize, error_out=False)
        camerainfo_list = pagination.items
        for camerainfo in camerainfo_list:
            camera_dict = dict()
            camera_dict["camera_id"] = camerainfo.id
            camera_dict["camera_name"] = camerainfo.camera_name
            data_list.append(camera_dict)
    except BaseException as e:
        # 接口调用失败
        logger.error(e)
        return get_res(-1, userdata)
    ret["code"] = 0
    ret["data"] = data_list
    ret["all_page"] = pagination.pages
    ret["page"] = pagination.page
    ret["all_data"] = pagination.total
    ret["userdata"] = userdata
    logger.debug("返回的json是:{}".format(ret))
    return jsonify(ret)
コード例 #28
0
ファイル: ServiceApi.py プロジェクト: ccevan/deploy
def project_detail():
    """
    根据项目id查看项目详情,项目说明以及项目包含的服务等
    :return:
    """
    json_data = return_json(request)
    project_id = json_data.get("project_id", None)
    if not project_id:
        code = -1
        msg = "project_id is required"
        return response_tem(code=code, msg=msg)
    all_info = []
    try:
        search_param = {"is_delete": False, "id": project_id}
        proj_obj = Project.query.filter_by(**search_param).first()
        if not proj_obj:
            code = -1
            msg = "查询失败, 该项目不存在或已被删除"
            return response_tem(code=code, msg=msg)
        project_name = proj_obj.project_name
        all_service_obj = proj_obj.services
        all_service_obj = [
            service for service in all_service_obj
            if service.is_delete == False
        ]
        service_info_list = []
        for service_obj in all_service_obj:
            service_info = {
                "service_id": service_obj.id,
                "service_name": service_obj.service_name,
                "service_instruction": service_obj.service_instruction
            }
            service_info_list.append(service_info)
        proj_info = {
            "project_name": project_name,
            "service_info": service_info_list
        }
        all_info.append(proj_info)
        code = 0
        msg = "查询成功"
    except Exception as e:
        logger.error(e)
        code = -1
        msg = "查询失败"
    return response_tem(code=code, msg=msg, data=all_info)
コード例 #29
0
def add_channel():
    """添加通道"""
    if not request.content_type == 'application/json':
        return render_response(-1,msg="Content-type must be application/json.")

    form = ChannelForm.from_json(request.json)
    if not form.validate():
        msg = "Content-type error:{}".format(form.errors)
        logger.warning(msg)
        return render_response(-1, msg=msg)
    try:
        kwargs = form.data
        channel = Channel(**kwargs)
        channel.add()
    except Exception as e:
        logger.error(e)
        return render_response(-1, msg='database error')
    return render_response(0)
コード例 #30
0
def start_task():
    """
    启动已经暂停的任务
    """
    if not request.content_type == 'application/json':
        return render_response(-1,
                               msg="Content-type must be application/json.")

    userdata = request.json.get('userdata')

    task_ids = request.json.get('task_id')
    if not task_ids:
        return render_response(-1, msg="task_id is required.")

    if type(task_ids) == str:
        task_ids = [task_ids]

    for task_id in task_ids:
        task = Task.query.get(task_id)

        if not task:
            msg = "task not found."
            return render_response(code=-1, msg=msg, userdata=userdata)

        task_helper.assign_task(task.id)

        try:
            scheduler.resume_job(task_id)
        except Exception as e:
            logger.error(e)
            msg = "Startup failed. task may be already finished."
            # return render_response(code=-1, userdata=userdata, msg=msg)

        task.task_status = 1  # 任务状态1表示已启动
        try:
            db.session.add(task)
            db.session.commit()
        except Exception as e:
            logger.error(e)
            return render_response(code=-1,
                                   msg="database error.",
                                   userdata=userdata)

    return render_response(code=0, userdata=userdata)