前言
用 streamlit 搭建 web 页面比较容易,但要分享发布到互联网上,需要用到登录页面以进行验证,避免数据泄露和攻击。本文介绍如何简单快速的搭建登录页面。
代码框架
通过构建 check_password 函数,快速搭建登录表格和判断依据,利用. streamlit/secrets. toml 简单存储账号及密码。
Code
主要参考了 streamlit docs,做了一点优化。参考文件见后文。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
| import hmac import streamlit as st def check_password(): def login_form(): with st.form("Credentials"): col0,col1, col2 = st.columns([0.6,0.4, 2],vertical_alignment="top") with col0: st.write(" ") with col1: st.image("./utils/logo.png", width=75) with col2: st.markdown("## 水环境分析百宝箱") st.text_input("账号名称", key="username") st.text_input("账号密码", type="password", key="password") cols = st.columns([4, 1]) cols[1].form_submit_button("登录", on_click=password_entered) def password_entered(): """Checks whether a password entered by the user is correct.""" if st.session_state["username"] in st.secrets[ "passwords" ] and hmac.compare_digest( st.session_state["password"], st.secrets.passwords[st.session_state["username"]], ): st.session_state["password_correct"] = True del st.session_state["password"] del st.session_state["username"] else: st.session_state["password_correct"] = False if st.session_state.get("password_correct", False): return True login_form() if "password_correct" in st.session_state: st.error("😕 账号不存在或者密码不正确") return False if not check_password(): st.stop()
|
另外需在. Streamlit 文件夹下新建 secrets. Toml 配置文件,设置账号密码。
1 2 3
| [passwords] "guest" = "guest" "user1" = "user1"
|
效果预览
虽然简陋但也完全够用了。
多页面应用
为了让其他子页面也能够实现必须登录才能访问,需要在代码前引用上述函数。
多页面结构如下:
1 2 3 4 5 6 7 8 9 10
| your-repository/ ├── .streamlit/ │ └── config.toml │ └── secrets.toml ├── pages/ │ ├── login.py │ ├── page1.py │ ├── page2.py │ └── page3.py └── app.py
|
前面的代码 login.py 中,page1.py 等子页面需在设置页面格式后(. set_page_config),添加下面代码实现调用登录验证。
1 2 3 4 5 6
| import streamlit as st st.set_page_config(page_title=" "}) from login import check_password if not check_password(): st.stop() # 继续子页面内容
|
至此结束。
参考资料
Streamlit docs : https://docs.streamlit.io/knowledge-base/deploy/authentication-without-sso
BY
纯个人经验,如有帮助,请收藏点赞,如需转载,请注明出处。
微信公众号:环境猫 er
CSDN : 细节处有神明
个人博客: https://maoyu92.github.io/