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

This topic was automatically closed 365 days after the last reply. New replies are no longer allowed.