Hello !
I’m trying to build a streamlit app with a radio button, and I want to store the value of the radio button in a local cache file. The idea is that if I shutdown my app, and restart it later, the latest value is loaded from the local cache file. I’m currently using this code:
from pathlib import Path
import streamlit as st
cache_file = Path(".streamlit_cache")
choices = ["a", "b", "c"]
index = 0
if not st.session_state.get("initialized") and cache_file.is_file():
with cache_file.open() as f:
selected_choice = f.read().splitlines()[0]
print(f"loading {selected_choice} from cache")
st.session_state["initialized"] = True
index = choices.index(selected_choice)
choice = st.radio("choices", choices, index=index)
print(f"choice is {choice}")
with cache_file.open("w") as f:
f.write(choice)
It almost works as I wish, but I still have one minor issue, here is how to reproduce it:
echo "b" > .streamlit_cache
streamlit run tmp.py
On the web browser, b
appears selected and the logs are:
loading b from cache
choice is b
as expected.
But then, if I click on c
on the web browser, a
appears selected instead of c
and the logs are:
choice is a
which is not the behavior I’m expected.
After that, the behavior of my app is the one I’m expecting.
Do you know how I can adapt my code to avoid this issue ?
Thanks
- Are you running your app locally or is it deployed?
locally - Share the full text of the error message (not a screenshot).
no error message, see the description above - Share the Streamlit and Python versions.
$ python -V Python 3.10.12 $ pip show streamlit | grep Version Version: 1.31.1