loginをアプリにつける方法

authentificationは面倒なので,streamlitのSharingでごまかしていたが,fast.apiで必要そうなので,streamlit-authentificatorをベースに作ってみた.

データベースは無料なのでDETAを使う.

Detaだとfast.apiもタダで公開できる(がまだベータ).

configファイルというのを使って認証オブジェクトを生成するが,それをまるごとDetaのNo SQLデータベースに保管しておく.Detaとのキーは.envに保管し,dotenvパッケージを使って読み込む.

from dotenv import load_dotenv
from deta import Deta
import os

load_dotenv(".env")
DETA_KEY = os.getenv("DETA_KEY")
deta = Deta(DETA_KEY)
db_config = deta.Base("config")

Strealit クラウドだと,App SettingのSecrets で TOML 形式で渡す.

DETA_KEY = " ここにキーを入れる "

DBからconfigを得て,認証オブジェクトを生成する.
cookieのキーはターミナルで生成しておく.

openssl rand -hex 32
import streamlit_authenticator as stauth

fetch = db_config.fetch()
config = fetch.items[0]
authenticator = stauth.Authenticate(
    config['credentials'],
    config['cookie']['name'],
    config['cookie']['key'],
    config['cookie']['expiry_days'],
    config['preauthorized']
)

後はstreamlit-authntificateパッケージの指示にしたがって,loginなどがstreamlitでできる.loginしているか否かはstreamlitのセッションに保管しておく.

 #ログイン 
name, authentication_status, username = authenticator.login('Login', location)
st.session_state["authentication_status"]=authentication_status
     

token発行などは自分でやる必要がある.ソースをみたら,まだ書いていないようなので,内部メソッドを使って自作する必要がある.たとえば,トークン発行は以下のように書ける.

    if st.sidebar.checkbox("Get Token"):
        try:            
            authenticator.exp_date =  authenticator._set_exp_date()
            token = authenticator._token_encode() 
            st.success('Get token successfully')
            st.write(token)
        except Exception as e:
            st.error(e)

トークンで認証してapiを使ってもらえばよいが,Excelのファイルを自動変換してくれるものでも準備しないと,たぶん使ってくれないだろう.

この記事が気に入ったらサポートをしてみませんか?