当前位置: 首页 > news >正文

86-python电网可视化项目-6

1. 实现下工单

     ------程序效果图:----
✅连接到MySQL数据库
⚡ 欢迎使用XXX电网管理系统====================================*****登录系统******
请输入用户名:admin
请输入用密码:admin
✅连接到MySQL数据库
恭喜您admin登录成功了====================================国家电网管理系统
====================================
当前用户: 系统管理员 (admin)
1. 查看变电站列表
2. 查看设备列表
3. 查看最新电力数据
4. 创建工单
5. 查看我的工单
6. 系统日志
7. 退出
------------------------------------
请选择功能[请输入1--7之间的数字]:4
工单标题:test
工单的描述test
✅连接到MySQL数据库
选择关联的设备
1. 东区变电站           
2. 中心变电站           
选择变电站1
✅连接到MySQL数据库
您选择了东区变电站的设备
1. 电容器组C1 capacitor
选择设备:1
✅连接到MySQL数据库
指派给工程师:
1. engineer1 engineer
选择工程师1
优先级:low/medium/high/critical 默认的是[medium]: high
✅连接到MySQL数据库
工单创建成功!工单号是:1====================================国家电网管理系统
====================================
当前用户: 系统管理员 (admin)
1. 查看变电站列表
2. 查看设备列表
3. 查看最新电力数据
4. 创建工单
5. 查看我的工单
6. 系统日志
7. 退出
------------------------------------
请选择功能[请输入1--7之间的数字]:7
✅连接到MySQL数据库
已经退出系统,
实现代码:# -*- coding: utf-8 -*-
"""
@Project : 01-python-learn
@File    : main.py
@IDE     : PyCharm
@Author  : 刘庆东
@Date    : 2025/9/25 9:10主函数类
"""
from power_grid_system import system#和power_grid_system 类中的对象名保持一致
from database import db #数据库的操作
from datetime import datetime,timedeltadef main():print("⚡ 欢迎使用XXX电网管理系统")#登录while not system.current_user:#开发登录菜单if not login_menu():retry=input("登录失败,重试吗?(y/n)")if retry.lower() != "y":#用户输入的不是yprint("再见!")return #系统没有必要继续执行了#主循环while True:# 调用主菜单进行显示main_menu()# 登录成功了 看到了主菜单  接下来 做什么?try:choice=input("请选择功能[请输入1--7之间的数字]:").strip()if choice =='1':view_substations()elif choice =='2':view_equipment()elif choice =='3':passelif choice =='4':#创建工单create_work_orders()#有没有参数待会再说elif choice =='5':passelif choice =='6':passelif choice =='7':#退出系统 做登出功能system.login_out()print("已经退出系统,")break#结束循环else:print("无效选择,请重新输入:")except Exception as e:print(f"程序被中断,再见!原因是:{e}")break#程序终止了结束循环#查看变电站列表
def view_substations():# 查看变电站 代码要写在核心业务模块substations = system.get_substations()print("变电站列表:")print(f"{'ID':<4} {'名称':<15} {'位置':<20}"f" {'电压(KV)':<10} "f"{'容量(MA)':<10} {'状态':<10} {'负责人'}")print("_" * 36)for sub in substations:print(f"{sub['substation_id']:<4}"f"{sub['substation_name']:<15}"f"{sub['location']:<20}"f"{sub['voltage_level_kV']:<10}"f"{sub['capacity_MVA']:<10}"f"{sub['status']:<15}"f"{sub['operator_name']}")#查看设备列表
def view_equipment():#获取所有的变电站substations=system.get_substations()if not substations:print("暂无变电站数据")returnprint("请选择变电站:")for i,sub in enumerate(substations,1):print(f"{i}. {sub['substation_name']:<15} {sub['location']:<20}")try:choice=int(input("请选择编号:"))-1if 0<=choice<len(substations):# 获取你选择的变电站selected_sub = substations[choice]#获取变电站下面的设备信息equipments=system.get_equipment_by_substation_id(selected_sub['substation_id'])print(f"变电站{sub['substation_name']}的设备列表:")print("-"*36)#你们写一下 这里的信息 参考68行print(f"{'ID':<4} {'名称':<20} {'类型':<12} {'型号':<15} {'序列号':<15} {'状态'}")print("-" * 36)for eq in equipments:print(f"{eq['equipment_id']:<4} {eq['equipment_name']:<20} {eq['equipment_type']:<12} "f"{eq['model']:<15} {eq['serial_number']:<15} {eq['status']}")#你们补全这列print("-"*36)except Exception as e:print(f"请输入有效的数字:{e}")#创建工单
def create_work_orders():title=input("工单标题:").strip()#工单标题description=input("工单的描述").strip() #工单的描述#获取设备列表substations=system.get_substations()#获取到变电站信息if not substations:print("没有可用的变电站")returnprint("选择关联的设备")for i,sub in enumerate(substations,1):print(f"{i}. {sub['substation_name']:<15} ")#维护某个变电站中的某个设备信息   比如 马坡变电站  136号设备try:sub_choice=int(input("选择变电站"))-1if sub_choice<0 or sub_choice>=len(substations):print("无效的选择")return#正常选择selected_sub = substations[sub_choice]#选择了变电站后需要选择当前变电站里面的某个设备#获取具体的设备  根据变电站的idequipments=system.get_equipment_by_substation_id(selected_sub['substation_id'])if not equipments:print("该变电站木有设备")returnprint(f"您选择了{selected_sub['substation_name']}的设备")for i,eq in enumerate(equipments,1):print(f"{i}. {eq['equipment_name']} {eq['equipment_type']}")#选择设备信息eq_choice=int(input("选择设备:"))-1if eq_choice<0 or eq_choice>=len(equipments):print("无效选择")return#合法的选择 设备selected_eq= equipments[eq_choice]#选择工程师engineers=[u for u in system.get_users() if u['role']=='engineer']if not engineers:print("无空闲的工程师!")return#有工程师print("指派给工程师:")for i,eng in enumerate(engineers,1):print(f"{i}. {eng['username']} {eng['role']}")#看着上面的工程师列表 进行工程师的选择eng_choice=int(input("选择工程师"))-1if eng_choice<0 or eng_choice>=len(engineers):print("无效的选择")return# assigned_to INT COMMENT '指派给的用户ID,外键指向users表' 指定指派对象assigned_to=engineers[eng_choice]['user_id']#工单的 级别#等级 低 中 高 临界 low/medium/high/criticalpriority=input("优先级:low/medium/high/critical 默认的是[medium]: ").strip() or "medium"if priority not in ["low", "medium", "high", "critical"]:priority='medium'#不在上述范围 指定为默认值#创建工单start_time=(datetime.now() + timedelta(hours=1)).strftime('%Y-%m-%d %H:%M:%S')end_time=(datetime.now() + timedelta(hours=3)).strftime('%Y-%m-%d %H:%M:%S')order_id=system.create_work_order(title=title,#标题description=description,#描述equipment_id=selected_eq['equipment_id'],#关联设备IDsubstation_id=selected_sub['substation_id'],#关联变电站IDassigned_to=assigned_to,#assigned_topriority=priority,scheduled_start = start_time,scheduled_end = end_time)print(f"工单创建成功!工单号是:{order_id}")except Exception as e:print(f"输入有错误:{e}")#主菜单
def main_menu():#输出菜单print("\n" + "=" * 36)print("      国家电网管理系统")print("=" * 36)print(f"当前用户: {system.current_user['full_name']} ({system.current_user['role']})")print("1. 查看变电站列表")print("2. 查看设备列表")print("3. 查看最新电力数据")print("4. 创建工单")print("5. 查看我的工单")print("6. 系统日志")print("7. 退出")print("-" * 36)#登录菜单
def login_menu():print("\n" + "=" * 36)print(" *****登录系统******")username=input("请输入用户名:")password=input("请输入用密码:")#调用登录的方法success_login=system.login(username, password)#判断一下if success_login:print(f"恭喜您{username}登录成功了")return Trueelse:print(f"系统登录失败")return Falseprint("\n" + "=" * 36)if __name__ == '__main__':main()

实现代码:
# -*- coding: utf-8 -*-
"""
@Project : 01-python-learn
@File    : power_grid_system.py
@IDE     : PyCharm
@Author  : 刘庆东
@Date    : 2025/9/24 14:01核心业务类:刚开始认为技术最难其实 业务最难"""
# 1.导入各种包[模块]
from  database import db#数据库部分
import bcrypt #加密
"""
datetime 表示当前具体的时刻 2025年9月24日 下午02:06
timedelta 代表的是两个时间点之间的差值 比如说 14小时23分钟后进行休息
"""
from datetime import datetime,timedelta
import logging #日志相关from pyecharts import options as opts"""
Line 上课学过使用场景:股票走势、气温变化、销售额度Bar 上课学过使用场景:月业绩排名、各个地区的人口数量Pie 大饼图使用场景:市场份额占比、预算分配Gauge 仪表盘使用场景: KPI、进度、完成率Grid 布局网格使用场景: 将一个折线图 和一个柱状图并排显示 ! """
from pyecharts.charts import Line,Bar,Pie,Gauge,Gridfrom pyecharts.globals import ThemeType#主题class PowerGridSystem:def __init__(self):#构造方法self.current_user=None #当前的用户#登录功能def login(self,username,password):try:query="""select user_id,username,password_hash,role,full_name from userswhere username=%s and STATUS='active'"""#查询返回结果result= db.execute_query(query,(username,))if result:#获取的是第一行数据user =result[0]if bcrypt.checkpw(password.encode('utf-8'),user['password_hash'].encode('utf-8')):#if password=='admin':self.current_user=user #将用户信息赋值给 current_user#返回之前进行日志的记录工作self.log_action("login","user",user['user_id'],f"用户{username}登录")return True#代表登录成功了except Exception as e:logging.error(f"登录失败{e}")return False#所有的操作 都需要进行日志的记录def log_action(self,action, target_type, target_id, details):query="""insert into system_logs (user_id, action, target_type, target_id, details)values (%s,%s,%s,%s,%s)"""#获取user_iduser_id= self.current_user['user_id'] if self.current_user else Nonedb.execute_update(query,(user_id,action,target_type,target_id,details))#登出的方法def login_out(self):if self.current_user:#用户不为空# 先进行日志的记录self.log_action("logout",'user',self.current_user['user_id'],f"用户{self.current_user['username']}登出")self.current_user = None#给当前的登录用置空#获取变电站信息def get_substations(self):#操作数据库的sql语句  任务query="""select s.*,u.full_name as operator_name from substations sleft join users u on s.operator_id = u.user_idorder by s.substation_name;    """return  db.execute_query(query)#通过变电站的id获取设备信息def get_equipment_by_substation_id(self,substation_id):sql="""select e.*,s.substation_name from equipment e join substations s on e.substation_id = s.substation_idwhere e.substation_id=%sorder by  e.equipment_name"""#执行通用的方法return db.execute_query(sql,(substation_id,))#获取工程师def get_users(self):query="""select user_id,username,password_hash,role,full_name from users"""return db.execute_query(query)"""order_id=system.create_work_order(titile=titile,#标题description=description,#描述equipment_id=selected_eq['equipment_id'],#关联设备IDsubstation_id=selected_sub['substation_id'],#关联变电站IDassigned_to=assigned_to,#assigned_topriority=priority,scheduled_start = datetime.now() + timedelta(hours=1),scheduled_end = datetime.now() + timedelta(hours=3))"""def create_work_order(self,title,description,equipment_id,substation_id,assigned_to,priority,scheduled_start,scheduled_end):query="""insert into work_orders (title,description,equipment_id,substation_id,assigned_to,priority,scheduled_start,scheduled_end)values (%s,%s,%s,%s,%s,%s,%s,%s)"""return db.execute_update(query,(title,description,equipment_id,substation_id,assigned_to,priority,scheduled_start,scheduled_end))#测试
system= PowerGridSystem()
#system.login("admin","admin")
http://www.dtcms.com/a/411245.html

相关文章:

  • 长乐住房和城乡建设局网站wordpress文章页面
  • 技术拐点将至:AI 大模型的挑战突围与产业重构
  • 青海省住房和城乡建设部网站关键词排名优化软件价格
  • 图片做多的网站是哪个邢台移动网站设计
  • TypeScript 中避免使用 @ts-ignore 的最佳方案
  • 数据传输一致性保障:如何避免‘少数据’或‘脏数据’?
  • Product Hunt 每日热榜 | 2025-09-26
  • 北京公司网站建设定制全国十大装修公司最有名的是
  • 鸿蒙开发入门经验分享:从零开始构建自己的HarmonyOS应用(ArkTS)
  • 解锁安全新维度:Cybersecurity AI (CAI) 助力提升网络安全效率!
  • FastAPI WebSocket 由浅入深的开发范例
  • 义乌免费做网站怎么创业呢白手起家
  • 网站维护运营好做吗建筑工程网络数据安全管理系统
  • 怎么制作外贸网站模板wordpress给会员发信
  • 西安跨境电商平台网站淘宝网网站设计分析
  • SSL 证书的重要性
  • 快速上手XXL-JOB
  • 分组交换总结
  • 亚马逊网站怎么做做网站一般注册商标哪个类
  • daily notes[54]
  • 机器学习——决策树详解
  • 万象EXCEL开发(六)excel单元格运算逻辑 ——东方仙盟金丹期
  • Redis数据结构和常用命令
  • 网站开发用什么开发无锡新吴区建设环保局网站
  • 深圳易捷网站建设计算机(网站建设与维护)
  • 智能微电网 —— 如何无缝集成分布式光伏 / 风电?
  • 苏州网站建设的公司万维网
  • 比较好的网站建设论坛wordpress纯静态化
  • 昆明云南微网站搭建西安网络建站
  • 怎么做二维码进入公司网站做网站推广优化哪家好