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)
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)
def count_energy(tags, start_time, end_time): try: result = 0.0 for tag in tags: sql = f'select sum(IncremenValue) as value from IncrementElectricTable where Address="{tag}" and CollectionDate between {start_time} and {end_time} ' data = db_session.execute(sql).fetchall() if data[0]['value'] is not None: result += float(data[0]['value']) else: result += 0.0 return result except Exception as err: db_session.rollback() db_session.close() my_log(err)
def count_floor_energy(tags, start_time, end_time, water_day_total, total_energy): try: total = 0.0 i = 0 floorData = [] print('total_energy_2: ', total_energy) for tag in tags: i += 1 floor_total_energy = 0.0 AreaName = f'厚德楼{i}楼' for item in tag: print('采集点: ', item) sql = f'select sum(IncremenValue) as value from IncrementElectricTable where Address="{item}" and CollectionDate between {start_time} and {end_time} ' data = db_session.execute(sql).fetchall() if data[0]['value'] is not None: floor_total_energy += float(data[0]['value']) total += floor_total_energy else: floor_total_energy += 0.0 total += 0.0 ratio = '%.2f' % (floor_total_energy / total_energy * 100) if i == 7 or i == 8: floorData.append({ 'areaName': AreaName, 'electricity': floor_total_energy, 'water': water_day_total, 'ratio': ratio }) else: floorData.append({ 'areaName': AreaName, 'electricity': floor_total_energy, 'water': 0.0, 'ratio': ratio }) return floorData except Exception as err: db_session.rollback() db_session.close() my_log(err) return []
def energys(): try: energy_type = request.values.get('energy_type') start_time = '"' + request.values.get('start_time') + '"' end_time = '"' + request.values.get('end_time') + '"' # start_time = '"' + '2020-01-31 23:00:00' + '"' # end_time = '"' + '22020-10-31 23:00:00' + '"' data = [] if energy_type == '电': sql = f'select AreaName,Address, sum(IncremenValue) as value from IncrementElectricTable where CollectionDate between {start_time} and {end_time} group by Address' results = db_session.execute(sql).fetchall() db_session.close() # print(results) for result in results: value = '%.2f' % result[2] if result[2] is not None else '0.0' data.append({ "AreaName": result[0], "Address": result[1], "Value": value, "StartTime": request.values.get('start_time'), "EndTime": request.values.get('end_time'), "Unit": "KW/h" }) else: sql = f'select AreaName,Address, sum(IncremenValue) as value from IncrementWaterTable where CollectionDate between {start_time} and {end_time} group by AreaName' results = db_session.execute(sql).fetchall() db_session.close() # print(results) for result in results: value = '%.2f' % float( result[2]) if result[2] is not None else '0.0' data.append({ "AreaName": result[0], "Address": result[1], "Value": value, "StartTime": request.values.get('start_time'), "EndTime": request.values.get('end_time'), "Unit": "m³" }) # data = [(result[0], result[1], '%.2f' % result[2], request.values.get('start_time'), request.values.get('end_time'), 'm³') for result in results] db_session.close() return json.dumps({ 'code': '200', 'mes': '查询成功', 'data': data }, ensure_ascii=False) except InvalidRequestError as e: print('/energy', '1') db_session.rollback() print('/energy', '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))) my_log(str(e)) return json.dumps({'code': '200', 'mes': '事务回滚'}, ensure_ascii=False) except Exception as e: # db_session.rollback() print(str(e)) return json.dumps({ 'code': '200', 'mes': '查询失败', 'error': str(e) }, ensure_ascii=False)
redis_coon.hset(REDIS_TABLENAME, 'indicator', json_data) start_m = datetime.now().strftime("%Y-%m-01 00:00:00") end_m = datetime.now().strftime("%Y-%m-01 00:00:00") # 当前月用电量总和 now_month_sql = f'select sum(IncremenValue) as value from IncrementElectricTable and CollectionDate between {start_m} and {end_m} ' # 楼层实时用能数据 L_tags = [['COM2.KT1F.总有功电量', 'COM2.LIGHT1F.总有功电量'], ['COM2.KT2F.总有功电量', 'COM2.LIGHT2F.总有功电量'], ['COM2.KT3F.总有功电量', 'COM2.LIGHT3F.总有功电量'], ['COM2.KT4F.总有功电量', 'COM2.LIGHT4F.总有功电量'], ['COM2.KT5F.总有功电量', 'COM2.LIGHT5F.总有功电量'], ['COM2.KT6F.总有功电量', 'COM2.LIGHT6F.总有功电量'], ['COM2.KT7F.总有功电量', 'COM2.LIGHT7F.总有功电量'], ['COM2.KT8F.总有功电量', 'COM2.LIGHT8F.总有功电量'], ['COM2.KT9F.总有功电量', 'COM2.LIGHT9F.总有功电量'], ['COM2.KT10F.总有功电量', 'COM2.LIGHT10F.总有功电量'], ['COM2.KT11F.总有功电量', 'COM2.LIGHT11F.总有功电量'], ['COM2.KT12F.总有功电量', 'COM2.LIGHT12F.总有功电量']] print('today_energy: ', today_energy) floor_data = count_floor_energy(L_tags, today_start_time, today_end_time, water_day_total, today_energy) data = json.dumps(floor_data, ensure_ascii=False) redis_coon.hset(REDIS_TABLENAME, 'floorData', data) print('结束计算能耗数据') time.sleep(180) except Exception as e: db_session.rollback() db_session.close() my_log(e)