bash
复制代码
实现代码:
# -*- 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,timedelta
def main():
print("⚡ 欢迎使用XXX电网管理系统")
#登录
while not system.current_user:
#开发登录菜单
if not login_menu():
retry=input("登录失败,重试吗?(y/n)")
if retry.lower() != "y":#用户输入的不是y
print("再见!")
return #系统没有必要继续执行了
#主循环
while True:
# 调用主菜单进行显示
main_menu()
# 登录成功了 看到了主菜单 接下来 做什么?
try:
choice=input("请选择功能[请输入1--7之间的数字]:").strip()
if choice =='1':
view_substations()
elif choice =='2':
view_equipment()
elif choice =='3':
pass
elif choice =='4':#创建工单
create_work_orders()#有没有参数待会再说
elif choice =='5':
pass
elif choice =='6':
pass
elif 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("暂无变电站数据")
return
print("请选择变电站:")
for i,sub in enumerate(substations,1):
print(f"{i}. {sub['substation_name']:<15} {sub['location']:<20}")
try:
choice=int(input("请选择编号:"))-1
if 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("没有可用的变电站")
return
print("选择关联的设备")
for i,sub in enumerate(substations,1):
print(f"{i}. {sub['substation_name']:<15} ")
#维护某个变电站中的某个设备信息 比如 马坡变电站 136号设备
try:
sub_choice=int(input("选择变电站"))-1
if sub_choice<0 or sub_choice>=len(substations):
print("无效的选择")
return
#正常选择
selected_sub = substations[sub_choice]
#选择了变电站后需要选择当前变电站里面的某个设备
#获取具体的设备 根据变电站的id
equipments=system.get_equipment_by_substation_id(selected_sub['substation_id'])
if not equipments:
print("该变电站木有设备")
return
print(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("选择设备:"))-1
if 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("选择工程师"))-1
if 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/critical
priority=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'],#关联设备ID
substation_id=selected_sub['substation_id'],#关联变电站ID
assigned_to=assigned_to,#assigned_to
priority=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 True
else:
print(f"系统登录失败")
return False
print("\n" + "=" * 36)
if __name__ == '__main__':
main()
bash
复制代码
实现代码:
# -*- 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 代表的是两个时间点之间的差值 比如说 1天 4小时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,Grid
from 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 users
where 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_id
user_id= self.current_user['user_id'] if self.current_user else None
db.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 s
left join users u on s.operator_id = u.user_id
order 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_id
where e.substation_id=%s
order 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'],#关联设备ID
substation_id=selected_sub['substation_id'],#关联变电站ID
assigned_to=assigned_to,#assigned_to
priority=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")