Я пытался отделить authedicator.logout() от функцию login() первого файла Python и вызовите ее в другом файле внутри блока st.session_state['page'] = 'dashboard'. Также пробовал некоторые другие вещи, такие как вызов run_app() внутри блока st.session_state['page'] = 'dashbpard', но мне не удалось этого добиться. Я хочу, чтобы когда я нажимал «Выйти», чтобы выйти из блока st.session_state['page'] = 'dashboard' и перенаправиться на блок st.session_state['page'] = 'login'.
Первый файл Python с логином:
Код: Выделить всё
import streamlit as st
import mysql.connector
from mysql.connector import Error
import streamlit_authenticator as stauth
from Streamlit_app import run_app
def read_db_config(file_path="D:\\Diploma thesis\\mysqldb_config.txt"):
config = {}
with open(file_path, 'r') as f:
for line in f:
key, value = line.strip().split('=')
config[key] = value
return config
def create_connection():
config = read_db_config()
try:
connection = mysql.connector.connect(
host=config.get("host"),
user=config.get("user"),
password=config.get("password"),
database=config.get("database"),
port=int(config.get("port"))
)
if connection.is_connected():
return connection
except Error as e:
st.error(f"Error: {e}")
return None
def fetch_credentials(connection):
cursor = None
try:
cursor = connection.cursor(dictionary=True)
query = "SELECT first_name, last_name, username, password, date_of_birth FROM users"
cursor.execute(query)
users = cursor.fetchall() # This returns a list of dictionaries
return users # Return the list of user records
except Error as e:
st.error(f"Error: {e}")
return []
finally:
if cursor:
cursor.close()
def format_credentials(users):
formatted_credentials = {
"usernames": {}
}
for user in users:
username = user['username']
first_name = user['first_name']
last_name = user['last_name']
password = user['password']
date_of_birth = user['date_of_birth']
formatted_credentials["usernames"][username] = {
"name": first_name,
"last_name": last_name,
"password": password,
"date_of_birth": date_of_birth
}
return formatted_credentials
def login():
conn = create_connection()
credentials = format_credentials(fetch_credentials(conn))
if credentials:
authenticator = stauth.Authenticate(
credentials=credentials,
cookie_name="auth",
cookie_key="my_key",
cookie_expiry_days=3,
)
name, auth_status, username = authenticator.login()
if auth_status is None:
st.warning("Please enter your credentials")
return auth_status
if auth_status is False:
st.error("Username or Password is incorrect")
return auth_status
if auth_status:
user_info = credentials['usernames'][username]
first_name = user_info["name"]
last_name = user_info["last_name"]
date_of_birth = user_info["date_of_birth"]
#st.success(f"Welcome {first_name} {last_name}!")
st.sidebar.subheader(f'Welcome {first_name} {last_name}!')
#st.sidebar.write(f"Username: {username}")
#st.sidebar.write(f"Date of Birth: {date_of_birth}")
chat_dir = "D:\\Diploma thesis\\Profiles\\" + username + "\\Chat sessions"
run_app(chat_dir)
authenticator.logout('Log Out', 'sidebar')
return auth_status
else:
st.error("No users found in the database")
conn.close()
#st.title('Login System')
#login()
# Note: The line below is not part of the Streamlit app execution
# You run the Streamlit app with the following command:
# python -m streamlit run Streamlit_login.py
Код: Выделить всё
import streamlit as st
from Streamlit_signup import sign_up
from Streamlit_login import login
if 'page' not in st.session_state:
st.session_state['page'] = 'login'
if 'auth_status' not in st.session_state:
st.session_state['auth_status'] = None
if st.session_state['page'] == 'login':
st.title('AI Chatbot')
col_1, col_2 = st.columns([14, 2])
with col_2:
if st.button(":green[Sign up]"):
st.session_state['page'] = 'sign_up'
st.rerun()
auth_status = login()
st.write("auth status: " + str(auth_status))
if auth_status:
st.write("auth status in dashboard: " + str(auth_status))
st.session_state['page'] = 'dashboard'
st.session_state['auth_status'] = auth_status
st.rerun()
elif st.session_state['page'] == 'sign_up':
st.title("Sign Up Form")
sign_up()
if st.button("Back to Login"):
st.session_state['page'] = 'login'
st.session_state['auth_status'] = False
st.rerun()
elif st.session_state['page'] == 'dashboard':
st.title("Dashboard")
st.write(st.session_state['auth_status'])
login()
st.session_state['page'] = 'login'
# Note: The line below is not part of the Streamlit app execution
# You run the Streamlit app with the following command:
# python -m streamlit run MyChatBotApp.py
[*]Страница входа
Панель управления
Остается на панели управления после выхода из системы
Подробнее здесь: https://stackoverflow.com/questions/790 ... -streamlit