Exemplo n.º 1
0
def repairs():
    """
    添加设备维修任务
    :return:
    """
    if request.method == 'GET':
        data = db_session.query(Repair).all()
        return json.dumps({
            'code': '10001',
            'message': '操作成功',
            'data': data
        },
                          cls=AlchemyEncoder,
                          ensure_ascii=False)
    if request.method == 'POST':
        json_data = request.values
        data = Repair(EquipmentCode=json_data.get('EquipmentCode'),
                      No=get_no(json_data.get('ApplyTime')),
                      Worker=current_user.Name,
                      ApplyTime=json_data.get('ApplyTime'),
                      FaultExpound=json_data.get('FaultExpound'))
        equipment = db_session.query(Equipment).filter_by(
            EquipmentCode=json_data.get('EquipmentCode')).first()
        equipment.Status = '待接单'
        db_session.add_all([data, equipment])
        db_session.commit()
        db_session.close()
        return json.dumps({
            'code': '10000',
            'message': '操作成功'
        },
                          cls=AlchemyEncoder,
                          ensure_ascii=False)
Exemplo n.º 2
0
def error_handler(e):
    """全局捕获异常"""
    db_session.rollback()
    re_path = request.path
    re_func = request.url_rule.endpoint.split('.')[1]
    re_method = request.method
    # root_path = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
    # file_path = os.path.join(root_path, 'logs\\logs.txt')
    ip = socket.gethostbyname(socket.gethostname())
    now_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    result = f"{now_time} -- {ip} -- {re_path} -- {re_func} -- {re_method} -- {e}"
    print(result)
    db_session.add(
        RunError(Time=now_time,
                 IP=ip,
                 Path=re_path,
                 Func=re_func,
                 Method=re_method,
                 Error=e))
    db_session.commit()
    db_session.close()
    my_log(e)
    return json.dumps({
        'code': '2000',
        'msg': result
    },
                      cls=MyEncoder,
                      ensure_ascii=False)
Exemplo n.º 3
0
def get_index_equipment():
    try:
        query_type_data = db_session.query(
            Equipment.EquipmentType).filter_by().all()
        query_floor_data = db_session.query(
            Equipment.Floor).filter_by().order_by(Equipment.Floor.asc()).all()
        equipment_type = list(set(i[0] for i in query_type_data))
        equipment_floor = list(set(i[0] for i in query_floor_data))
        data = []
        for item_floor in equipment_floor:
            result = {"楼层": item_floor}
            for item_type in equipment_type:
                query_result = db_session.query(Equipment).filter_by(
                    Floor=item_floor, EquipmentType=item_type).all()
                result[item_type] = len(query_result)
            data.append(result)
        db_session.close()
        return json.dumps({
            'code': '200',
            'mes': '查询成功',
            'data': data
        },
                          ensure_ascii=False)
    except InvalidRequestError as e:
        print('/IndexEquipment', '1')
        db_session.rollback()
        print('/IndexEquipment', '2')
        re_path = request.path
        re_func = request.url_rule.endpoint.split('.')[1]
        re_method = request.method
        # root_path = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
        # file_path = os.path.join(root_path, 'logs\\logs.txt')
        ip = socket.gethostbyname(socket.gethostname())
        now_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        db_session.add(
            RunError(Time=now_time,
                     IP=ip,
                     Path=re_path,
                     Func=re_func,
                     Method=re_method,
                     Error=str(e)))
        db_session.commit()
        my_log(str(e))
        return json.dumps({'code': '200', 'mes': '事务回滚'}, ensure_ascii=False)
    except Exception as e:
        print(str(e))
        return json.dumps({
            'code': '200',
            'mes': '查询失败',
            'error': str(e)
        },
                          ensure_ascii=False)
Exemplo n.º 4
0
def repair_tasks(p):
    """
    更新维修任务表的状态
    :param p: 更改工单状态
    :return:
    """
    if p == 'jiedan':
        json_data = request.values
        data = db_session.query(Repair).filter_by(
            No=json_data.get('No')).first()
        data.Status = '维修中'
        data.ReceiveWorker = current_user.Name
        data.ReceiveTime = json_data.get('Time')
        equipment = db_session.query(Equipment).filter_by(
            EquipmentCode=json_data.get('EquipmentCode')).first()
        equipment.Status = '维修中'
        db_session.add_all([data, equipment])
        db_session.commit()
        db_session.close()
        return json.dumps({
            'code': '10001',
            'message': '操作成功'
        },
                          cls=AlchemyEncoder,
                          ensure_ascii=False)
    if p == 'over':
        json_data = request.values
        data = db_session.query(Repair).filter_by(
            No=json_data.get('No')).first()
        task_data = RepairTask(EquipmentCode=data.EquipmentCode,
                               No=data.No,
                               Status='维修完成',
                               Worker=data.Worker,
                               ReceiveWorker=data.ReceiveWorker,
                               Content=json_data.get('Content'),
                               ApplyTime=data.ApplyTime,
                               ReceiveTime=data.ReceiveTime,
                               EndTime=json_data.get('EndTime'))
        equipment = db_session.query(Equipment).filter_by(
            EquipmentCode=json_data.get('EquipmentCode')).first()
        equipment.Status = '运行中'
        db_session.add_all([task_data, equipment])
        db_session.delete(data)
        db_session.commit()
        db_session.close()
        return json.dumps({
            'code': '10001',
            'message': '操作成功'
        },
                          cls=AlchemyEncoder,
                          ensure_ascii=False)
Exemplo n.º 5
0
def keep_plans():
    """保养计划"""
    try:
        json_data = request.get_json()
        # equipments = ['XXF-2', 'XXF-1', 'PYF-1']
        equipments = json_data.get('EquipmentCode')
        if len(equipments) == 1:
            equipment_code = equipments[0]
        else:
            equipment_code = '  '.join(equipments)
        work_time = add_date(json_data.get('WeekTime'),
                             json_data.get('StartTime'))
        work_type = json_data.get('Type')
        week_time = '单次' if work_type == '单次' else json_data.get('WeekTime')
        data = KeepPlan(EquipmentCode=equipment_code,
                        No=get_no(json_data.get('ApplyTime')),
                        Worker=current_user.Name,
                        ApplyTime=json_data.get('ApplyTime'),
                        Type=json_data.get('Type'),
                        StartTime=json_data.get('StartTime'),
                        Describe=json_data.get('Describe'),
                        WorkTime=work_time,
                        WeekTime=week_time)
        db_session.add(data)
        db_session.commit()
        db_session.close()
        return json.dumps({
            'code': '10001',
            'message': '操作成功'
        },
                          cls=AlchemyEncoder,
                          ensure_ascii=False)
    except Exception as e:
        logger.error(e)
        insertSyslog("error", "保养计划表添加错误:" + str(e), current_user.Name)
        return json.dumps({
            'code': '20002',
            'message': str(e)
        },
                          cls=AlchemyEncoder,
                          ensure_ascii=False)
Exemplo n.º 6
0
def my_log(e):
    """
    程序日志记录
    :param e:捕获异常参数`
    """
    root_path = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
    file_path = os.path.join(root_path, 'run_log\\logs.txt')
    call_func = sys._getframe().f_back.f_code.co_name
    # user = login_user if login_user is None else 'no login'
    with open(file_path, 'a', encoding='utf-8') as f:
        print(f'{datetime.datetime.now()} -- {call_func} --- {e}' + "\n\n")
        f.write(f'{datetime.datetime.now()} -- {call_func} --- {e}' + "\n\n")
        f.close()
        db_session.add(
            RunError(
                Time=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
                Func=call_func,
                Error=e))
        db_session.commit()
        db_session.close()
    return '日志写入成功'
Exemplo n.º 7
0
def read_Excel(file_dir):
    # 打开文件
    workbook = xlrd.open_workbook(file_dir)
    if workbook:
        # 获取所有sheet
        # print(workbook.sheet_names())# [u'sheet1', u'sheet2']
        # sheet1_name = workbook.sheet_names()[0]
        # 根据sheet索引或者名称获取sheet内容
        # sheet1 = workbook.sheet_by_index(0)
        sheet1 = workbook.sheet_by_name('2020年月度能耗记录')

        # sheet的名称,行数,列数
        print(sheet1.name, sheet1.nrows, sheet1.ncols)
        list1 = [
            '2020-01-31 23:00:00', '2020-02-29 23:00:00',
            '2020-03-31 23:00:00', '2020-04-30 23:00:00',
            '2020-05-31 23:00:00', '2020-06-30 23:00:00',
            '2020-07-31 23:00:00', '2020-08-31 23:00:00',
            '2020-09-30 23:00:00', '2020-10-31 23:00:00'
        ]
        if sheet1:
            if sheet1.nrows <= 0:
                return
            for row in range(1, sheet1.nrows):
                row_value = sheet1.row_values(row)
                if row_value[0] is None or row_value[0] == '':
                    continue
                i = 1
                for item in list1:
                    db_session.add(
                        IncrementElectricTable(Address=row_value[0],
                                               IncremenValue='%.2f' %
                                               row_value[i],
                                               CollectionDate=item,
                                               IncremenType='电表'))
                    db_session.commit()
                    i += 1
Exemplo n.º 8
0
def keep_tasks():
    """保养任务表"""
    try:
        query_data = db_session.query(KeepPlan).filter_by(Status='待保养').all()
        if request.method == 'GET':
            # 每页多少条
            limit = int(request.values.get('limit', '5'))
            # 当前页
            offset = int(request.values.get('offset', '1'))
            for item in query_data:
                q = db_session.query(KeepTask).filter_by(No=item.No).first()
                if not q and get_time_stamp(item.WorkTime):
                    data = KeepTask(EquipmentCode=item.EquipmentCode,
                                    No=item.No,
                                    Worker=item.Worker,
                                    Status=item.Status,
                                    ApplyTime=item.ApplyTime,
                                    StartTime=item.StartTime,
                                    WorkTime=item.WorkTime,
                                    WeekTime=item.WeekTime,
                                    Type=item.Type)
                    db_session.add(data)
                    db_session.commit()
                # if item.Type == '单次':
                #     pass
                # db_session.delete(item)
                # db_session.commit()
            data = db_session.query(KeepTask).order_by(
                KeepTask.ApplyTime.desc()).limit(limit).offset(
                    (offset - 1) * limit)
            total = db_session.query(KeepTask).count()
            return json.dumps(
                {
                    'code': '10001',
                    'message': '操作成功',
                    'data': {
                        'rows': data.all(),
                        'total': total
                    }
                },
                cls=AlchemyEncoder,
                ensure_ascii=False)
        if request.method == 'POST':
            json_data = request.values
            no = json_data.get('No')
            end_time = json_data.get('EndTime')
            content = json_data.get('Content')
            item = db_session.query(KeepTask).filter_by(No=no).first()
            data = KeepRecord(EquipmentCode=item.EquipmentCode,
                              No=no,
                              Worker=item.Worker,
                              Status='已完成',
                              Type=item.Type,
                              KeepWorker=current_user.Name,
                              ApplyTime=item.ApplyTime,
                              StartTime=item.StartTime,
                              Describe=item.Describe,
                              Content=content,
                              WeekTime=item.WeekTime,
                              EndTime=end_time)
            db_session.delete(item)
            db_session.commit()
            keep_plan = db_session.query(KeepPlan).filter_by(No=no).first()
            if keep_plan and keep_plan.Type == '周期':
                keep_plan.WorkTime = add_date(keep_plan.WeekTime,
                                              keep_plan.WorkTime)
                db_session.add_all([data, keep_plan])
                db_session.commit()
                db_session.close()
                return json.dumps({
                    'code': '10001',
                    'message': '操作成功'
                },
                                  cls=AlchemyEncoder,
                                  ensure_ascii=False)
            else:
                db_session.delete(keep_plan)
                db_session.add(data)
                db_session.commit()
                db_session.close()
            return json.dumps({
                'code': '10001',
                'message': '操作成功'
            },
                              cls=AlchemyEncoder,
                              ensure_ascii=False)
    except Exception as e:
        logger.error(e)
        insertSyslog("error", "保养任务表修改错误:" + str(e), current_user.Name)
        return json.dumps({
            'code': '20002',
            'message': str(e)
        },
                          cls=AlchemyEncoder,
                          ensure_ascii=False)