pythonslidersession-statestreamlit

Problem with Streamlit session_state on ranged slider


I'm trying to implement a ranged slider in my streamlit app. It should define which content to show below on the website. More accurately, I want to show texts which are stored with a "date" value, showing, when to publish this specific text. I'm querying my SQL database to define the range the slider should present as min_value and max_ value. But when using the slider, the default values get reestablished after the apps rerun.

Im starting with the following SQL query:

cursor = connection.cursor()
query = "SELECT MIN(scheduled_pub) FROM tbl_article;"
cursor.execute(query)
oldest_date = cursor.fetchone()[0]
cursor.close()
    
today = datetime.now()

Now i'm handing these two dates over as parameters to my ranged slider, by default showing every date from my first database entry up to today.

range_selected = st.slider(label="range",
                           min_value=oldest_date,
                           max_value=today,
                           value=(oldest_date, today))

When running the app the slider shows up as intended, but as soon as I change one of the two values, the app gets rerun and resets the value to default. I assume that's because the SQL query gets processed again and the variables are set to those values again. I'm aware of the session_state fucntionality, but I can't quite get my head around it. All the documentation and tutorials are showing how to use session_state with buttons. I tried several ways of declaring the if "range" not in session_state: and other code snippets i found somewhere, but I was not able to get the app running as intended and it drives me crazy. I get what the session_state does, it stores a value even after a rerun. But I don't understand the syntax and how to declare what to save and in which case.

I would appreciate any help! Thanks a lot.


Solution

  • I tried several ways of declaring the if "range" not in session_state: and other code snippets i found somewhere, but I was not able to get the app running as intended and it drives me crazy. I get what the session_state does, it stores a value even after a rerun. But I don't understand the syntax and how to declare what to save and in which case.

    The if statement is how you would initialize the session state value at the beginning of the script – e.g.:

    if "range" not in st.session_state:
       st.session_state.range = <your desired default value>
    

    To update the value of range later in the script, you can use the following syntax:

    st.session_state.range = <your desired range value>
    

    You can also use this syntax:

    st.session_state['range'] = <your desired range value>