Streamlit Autorefresh
Streamlit Autorefresh is a Python library that provides a simple way to automatically refresh Streamlit applications. It works by implementing a frontend-based timer that periodically pings the Streamlit server, triggering a rerun of the application script. This component helps in building dashboards or real-time applications that need to display regularly updated information without relying on problematic infinite loops in the backend. The current version is 1.0.1, with releases typically tied to bug fixes or minor enhancements.
Warnings
- gotcha Using a very small `interval` can lead to high CPU utilization on the server, as it constantly pings Streamlit to rerun the script. This can consume significant computing resources.
- gotcha If the `key` parameter is not provided or changed, `st_autorefresh` might remount on the Streamlit frontend, leading to a loss of its internal state (like the refresh count).
- gotcha User interactions (e.g., button clicks, widget changes) within the set refresh interval will cause a full Streamlit rerun and effectively reset the `st_autorefresh` timer. This means refreshes might not occur at perfectly fixed intervals from the app's initial load if user interaction is frequent.
- gotcha The `streamlit-autorefresh` component works by having the browser ping the server. If the user's browser tab is closed, goes to sleep, or loses its WebSocket connection to the server (e.g., due to network issues or deployment environment timeouts), the auto-refresh mechanism will stop working.
Install
-
pip install streamlit-autorefresh
Imports
- st_autorefresh
from streamlit_autorefresh import st_autorefresh
Quickstart
import streamlit as st
from streamlit_autorefresh import st_autorefresh
import datetime
st.set_page_config(layout='centered', initial_sidebar_state='auto', page_title='Autorefresh Demo')
st.title("Streamlit Autorefresh Demo")
# Run the autorefresh every 2000 milliseconds (2 seconds) and stop after 100 refreshes
count = st_autorefresh(interval=2000, limit=100, key="myautocounter")
if count == 0:
st.write("Count is zero")
elif count % 3 == 0 and count % 5 == 0:
st.write("FizzBuzz")
elif count % 3 == 0:
st.write("Fizz")
elif count % 5 == 0:
st.write("Buzz")
else:
st.write(f"Current Count: {count}")
st.write(f"Last refreshed at: {datetime.datetime.now().strftime('%H:%M:%S')}")