Streamlitはシンプルでコード書きすいウェブアプリ開発ツールですが、デフォルトでログイン機能を備えていません。
この記事では、ユーザー認証の実装を簡単にするstreamlit-authenticatorライブラリを使用して、ログイン機能をStreamlitアプリに追加する方法を解説します。
Contents
前準備
環境
- Python 3.8+
- Streamlit
ライブラリのインストール
次のコマンドを実行して、streamlit-authenticator をインストールします。
pip install streamlit pip install streamlit-authenticator
<config.yaml>
cookie:
expiry_days: 30
key: some_signature_key
name: some_cookie_name
credentials:
usernames:
jsmith:
email: jsmith@gmail.com
failed_login_attempts: 0
first_name: John
last_name: Smith
logged_in: false
password: $2b$12$xbkFf2BCbqjFP6yMIpve8OCb86D2lFpuN43CAp6oPGXA4rC5do90a
roles:
- admin
- editor
- viewer
rbriggs:
email: rbriggs@gmail.com
failed_login_attempts: 0
first_name: Rebecca
last_name: Briggs
logged_in: false
password: $2b$12$JTt87KL15BogeciFGpBbpeiparfL/j6YhndkBplloEle/u68qMywy
roles:
- viewer
oauth2:
google:
client_id: null
client_secret: null
redirect_uri: null
microsoft:
client_id: null
client_secret: null
redirect_uri: null
tenant_id: null
pre-authorized:
emails:
- melsby@gmail.com
サンプルコード
import streamlit as st
import streamlit_authenticator as stauth
import yaml
from yaml.loader import SafeLoader
with open('config.yaml') as file:
config = yaml.load(file, Loader=SafeLoader)
# Pre-hashing all plain text passwords once
# stauth.Hasher.hash_passwords(config['credentials'])
authenticator = stauth.Authenticate(
config['credentials'],
config['cookie']['name'],
config['cookie']['key'],
config['cookie']['expiry_days']
)
try:
authenticator.login()
if st.session_state["authentication_status"]:
## ログイン成功
with st.sidebar:
st.markdown(f'## Welcome *{st.session_state["name"]}*')
authenticator.logout('Logout', 'sidebar')
st.divider()
st.write('# ログインしました!')
elif st.session_state["authentication_status"] is False:
## ログイン成功ログイン失敗
st.error('Username/password is incorrect')
elif st.session_state["authentication_status"] is None:
## デフォルト
st.warning('Please enter your username and password')
except Exception as e:
st.error(e)
with open('config.yaml', 'w') as file:
yaml.dump(config, file, default_flow_style=False)
おわりに
streamlit-authenticatorを使用することで、Streamlitアプリに簡単にログイン機能を追加できます。 使用する場合に実際のデータベースやクラウド環境と組み合わせて実装を書き換えてください。

コメント
[…] 関連記事:streamlit-authenticatorでログイン機能を追加する […]