Zuletzt aktiv 10 months ago

這段程式碼使用 Streamlit 和 streamlit-authenticator 來 管理使用者登入,透過 YAML 設定檔 儲存使用者憑證與 Cookie 配置,並提供 登入、登出 和 使用者驗證 功能。

Änderung 28c7439aa93e24d3bb56501b9f61709608fd02f6

streamlit_authentication_with_yaml.py Originalformat
1import streamlit as st # 匯入 streamlit 模組
2import streamlit_authenticator as stauth # 匯入 streamlit_authenticator 模組
3import yaml # 匯入 yaml 模組
4from yaml.loader import SafeLoader # 從 yaml.loader 匯入 SafeLoader
5
6with open("./config.yaml") as file: # 開啟名為 config.yaml 的檔案
7 config = yaml.load(file, Loader=SafeLoader) # 使用 SafeLoader 從檔案讀取配置資訊並存入 config 變數中
8
9authenticator = stauth.Authenticate( # 建立一個 stauth.Authenticate 的實例 authenticator
10 config["credentials"], # 使用配置中的 credentials 屬性
11 config["cookie"]["name"], # 使用配置中的 cookie 的 name 屬性
12 config["cookie"]["key"], # 使用配置中的 cookie 的 key 屬性
13 config["cookie"]["expiry_days"], # 使用配置中的 cookie 的 expiry_days 屬性
14 config["preauthorized"], # 使用配置中的 preauthorized 屬性
15)
16
17authenticator.login("Login", "main") # 進行登入驗證,並顯示 "Login" 按鈕,連接到 "main"
18
19if st.session_state["authentication_status"]: # 如果驗證狀態為真
20 authenticator.logout("Logout", "main", key="unique_key") # 顯示 "Logout" 按鈕,連接到 "main",並使用特定的 key
21 st.write(f'Welcome *{st.session_state["name"]}*') # 顯示歡迎訊息,使用 st.session_state 中的 name 屬性
22 st.title("Some content") # 顯示標題為 "Some content"
23elif st.session_state["authentication_status"] is False: # 如果驗證狀態為假
24 st.error("Username/password is incorrect") # 顯示錯誤訊息,提示使用者帳號或密碼不正確
25elif st.session_state["authentication_status"] is None: # 如果驗證狀態為空
26 st.warning("Please enter your username and password") # 顯示警告訊息,提示使用者輸入帳號和密碼
27
28if st.session_state["authentication_status"]: # 如果驗證狀態為真
29 try:
30 if authenticator.reset_password(st.session_state["username"], "Reset password"): # 嘗試重設密碼,並顯示 "Reset password" 按鈕
31 st.success("Password modified successfully") # 顯示成功訊息,提示密碼修改成功
32 except Exception as e: # 處理可能的例外狀況
33 st.error(e) # 顯示錯誤訊息,提示發生了例外狀況
34
35with open("./config.yaml", "w") as file: # 開啟名為 config.yaml 的檔案,以寫入模式
36 yaml.dump(config, file, default_flow_style=False) # 將配置資訊寫入檔案,不使用預設流風格
37