import streamlit as st
import mysql.connector
from mysql.connector import Error
import streamlit_antd_components as sac
db_config = {
'host': 'localhost',
'user': 'root',
'password': '791120',
'database': 'familyfinance'
#'raise_on_warnings': True
}
# CSS样式,用于隐藏Streamlit的默认导航菜单、页脚和页眉
hide_st_style = """
<style>
#MainMenu {visibility: hidden;}
footer {visibility: hidden;}
header {visibility: hidden;}
#root > div:nth-child(1) > div > div > div > div > section > div {padding-top: 0rem;}
</style>
"""
st.markdown(hide_st_style, unsafe_allow_html=True)# 应用CSS样式
def authenticate_user(username, password):
try:
connection = mysql.connector.connect(**db_config)
if connection.is_connected():
cursor = connection.cursor()
# 编写SQL查询,根据实际情况调整
query = "SELECT username, password,name FROM users WHERE username = %s AND password = %s"
cursor.execute(query, (username,password))
result = cursor.fetchone()
# 如果用户名存在且密码匹配,则返回True
if result :
return True, result[0],result[2] # 返回True和用户名
else:
return False, None,None
except Error as e:
st.write(f"Database error: {e}")
finally:
if connection.is_connected():
connection.close()
return False, None,None
# 初始化session状态,用于跟踪用户认证状态和当前登录用户
if "auth_status" not in st.session_state:
st.session_state["auth_status"] = 1 # 默认为未认证状态
auth_status = st.session_state["auth_status"] # 获取当前认证状态
if "auth_user" not in st.session_state: # 如果没有设置当前用户,则默认为"系统"
st.session_state["auth_user"] = "系统"
name = st.session_state["auth_user"] # 获取当前登录用户名
# 用户登录逻辑
if auth_status == 1:
st.sidebar.title("用户登录") # 设置侧边栏标题
# 在侧边栏添加用户名和密码输入框
username = st.sidebar.text_input("用户名")
password = st.sidebar.text_input("密码", type="password")
# 登录按钮的事件处理
if st.sidebar.button("登录"):
login_success, user_name,user_full_name = authenticate_user(username, password)
if login_success:
st.success("登录成功!") # 显示登录成功消息
st.session_state["auth_status"] = 2 # 更新认证状态为已认证
st.session_state["auth_user"] = user_name # 更新当前用户
user_tag = sac.Tag(user_full_name) # 使用用户姓名作为tag
st.rerun() # 重新运行应用以刷新界面
else:
st.error("用户名或密码错误!") # 显示错误消息
st.session_state["auth_status"] = 1 # 重置认证状态
# 用户已登录,显示侧边栏菜单
if auth_status == 2:
name = st.session_state["auth_user"]
with st.sidebar.container():
# 创建标签
user_tag = sac.Tag(name, color='orange', bordered=False)
quit = sac.Tag('注销', color='red', bordered=False)
# 目录
menu = sac.menu(
items=[
sac.MenuItem('当前登陆', icon="list",disabled=True, tag=user_tag),
sac.MenuItem('主页', icon="house-fill"),
sac.MenuItem('Dashboard', icon="speedometer"),
sac.MenuItem('图例', icon='pie-chart', type='divider', children=[
sac.MenuItem('柱形图', icon='1-circle'),
sac.MenuItem('仪表盘', icon='2-circle'),
]),
sac.MenuItem('退出登录', icon="x-circle-fill",tag=quit),
#sac.MenuItem(type="divider"),
sac.MenuItem('相关库',icon='megaphone',type='group', children=[
sac.MenuItem('StreamlitAntd', icon='github', disabled=False, href='https://nicedouble-streamlitantdcomponentsdemo-app-middmy.streamlit.app/'),
sac.MenuItem('Echarts', icon='globe-central-south-asia',disabled=False, href='https://echarts.apache.org/examples/zh/index.html#chart-type-line'),
sac.MenuItem('Pyecharts', icon='minecart-loaded', disabled=False, href='https://pyecharts.org/#/zh-cn/intro')
])
],
index=1,
key='menu',
open_all=False, indent=20,
format_func='title'
)
#sac.divider('作者公众号',icon='envelope')
#st.image('D:/houtu1.png',width=100)
if menu == '主页':
st.write("你自己的界面!!!")
elif menu == '退出登录':
with st.spinner("加载中……"):
st.session_state["auth_status"] = 1
st.rerun()