Reloading data from Database

Hi everyone!

I’m newbie here in the Streamlit world! And i was wondering if there’s any posibility to create a button to ‘clear cache’ and bring the new information from my database connection.

I don’t wanna make my cache expire in some time,. Just want to upload my info, make some filters and visalizations, and if the users wants to reload the info without losing the filters, just need to click some button and it’s done!

I know this option exist in the hamburguer menu, but when i publish my app, this option dissapears. And also for UX is easier to visualize the button in the main screen.

Thanks!

Hi @Camilojaravila, welcome to the Streamlit community!

Using a combination of session state and cache, you should be able to accomplish what you want. Because of the way st.cache works, if you add an argument to your function definition, such as rerun_counter, then any new combination of arguments to that function will cause it to run again.

As pseudocode:


import streamlit as st

if 'key' not in st.session_state:
    st.session_state['rerun_counter'] = 0

@st.cache
def dbfunction(conn, sql, rerun_counter):
    ....
    return df

df = dbfunction(conn, sql, st.session_state['rerun_counter']

if st.button("re-run database"):
    st.session_state['rerun_counter'] += 1

Effectively, when your app starts, the counter would be zero. So the same connection, same query, same counter value will be cached. When the person hits the button, the counter is now incremented, and that combination of arguments won’t exist in cache. So the function gets run again, gets cached, until the next time someone hits the button.

Best,
Randy

Wow! This really does the trick!!! Thanks a lot for this solution.

1 Like