0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Streamlitでのデータキャッシュ、セッションの管理

Posted at

本記事は自身の忘備録的な側面が強いです。

Streamlitのインストール

pip install streamlit

使い方

1. カスタムコンポーネントの作成

Streamlitでは、ReactやVue.jsなどのフロントエンドフレームワークを使用してカスタムコンポーネントを作成できる。カスタムコンポーネントを用いることで、独自のUIをアプリに組み込むことが可能。

import streamlit as st
import streamlit.components.v1 as components

# カスタムコンポーネントの定義
def my_component():
    components.html('<h1">カスタムコンポーネントによる出力</h1>')

my_component()

2. データのキャッシング

Streamlitでは@st.cache_dataデコレータを使用することで、データのキャッシングが可能。データの読み込みなどを高速化させたい場合に使用。以下に、st.cache_dataの異なるパラメータと使用例を示す。

st.cache_dataのパラメータ

  • ttl: キャッシュの有効期限を秒単位で指定します。指定した時間が経過するとキャッシュが無効化され、再計算が行われる
  • max_entries: キャッシュに保存するエントリの最大数を指定します。これを超えると、古いエントリから削除される
@st.cache_data(ttl=3600, max_entries=100)
def load_data():
    sample_data = {"name": "Streamlit Study", "description": "cache sample"}
    return sample_data

data = load_data()
st.write("キャッシュされたデータ:", data)

st.cache_resourceの使用

st.cache_resourceは、リソースのキャッシングに使用される。例えば、DB接続やAPIクライアントのインスタンス化に利用可能。

イメージとしては以下のような感じ

@st.cache_resource
def get_database_connection():
    connection = create_database_connection()
    return connection

db_connection = get_database_connection()

キャッシュを無効化するには、st.cache_data.clear()st.cache_resource.clear()を使用。

3. セッションの管理

Streamlitでは、セッション状態を管理するためのst.session_stateが利用可能。同一タブ内のセッション保持が可能になる。
以下に、セッション管理のサンプルを示す。

セッションのエンティティ登録

セッションに新しいエンティティを登録するには、st.session_stateに新しいキーを追加する。

if "username" not in st.session_state:
    st.session_state.username = "Guest"

def update_username():
    # st.session_state.update()を使って更新
    st.session_state.update(username=st.session_state.input_username)

st.text_input("名前を入力:", key="input_username", value=st.session_state.username, on_change=update_username)
st.write(f"こんにちは, {st.session_state.username}サン!")

*基本的にSPAなので、リロードをするとセッションが消えてしまう。
永続化を考えるのであれば外部DBに保存するなどの仕組みが必要?

4. APIとの連携

requestsで叩いたデータの表示

import requests

response = requests.get("https://api.example.com/data")
data = response.json()
st.write(data)

特に凝った実装はなさそう。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?