How to prevent the reloading of the whole page when I let the user to perform an action

Hello everyone,

I am building a page which let the user to run a query against my database, once I have the data I would like to perform a simple exploratory data analysis of the data.

The problem arise when, at button of the page, I let the user choose any column of the data set with a selectbox to make a countplot. When the user perform that action, every single element of my page is rendered again and it creates a really poor user experience with the page.

When I load the data I use the decorator of cache with the allow_output_mutation option set true

5 Likes

Hi @Capi_hacendado -

Re-running top-to-bottom is the core of the Streamlit execution model, and where you don’t want to re-run things you can use st.cache (which you’ve indicated you’re using). So it sounds like you are doing what you’re supposed to.

Can you post a code snippet that demonstrates the problem?

Best,
Randy

Hi @randyzwitch thank you so much for answer.

You can see here a snippet of my code

            with st.beta_expander('Grafical distribution of the columns', expanded=False):
            fig_hist, ax = plt.subplots(figsize=(50, 30))
            ax.xaxis.set_major_formatter(plt.FuncFormatter(format_func))
            ax.yaxis.set_major_formatter(plt.FuncFormatter(format_func))
            df.hist(bins=30, color='r', ax=ax, xrot=90)
            fig_hist.tight_layout()
            st.pyplot(fig_hist, clear_figure=True)
        
        with st.beta_expander('Explore Categorical Columns', expanded=False):
            fig_count = plt.figure(figsize=[25, 12])
            hue_column = None
            column = st.selectbox('Choose Column', ['<select>'] + df.columns.tolist())
            if not column == '<select>':
                a = sns.countplot(x=column, hue=hue_column, data=df)
                a.set_xlabel(f'{column}', fontsize=24)
                a.set_ylabel(f'Count', fontsize=24)
                st.pyplot(fig_count, clear_figure=True)

In my use case scenario, moreover to show a distribution of the columns dataframe, I want to show a count plot of the categorical columns. So my problem comes when an user choose an specific column, the whole page will rerun, producing a terrible user experience. Most probably I am making a bad use of it

Again thank you for your answer

3 Likes

I believe this is a limitation of Streamlit. Currently, some app designs cannot be accomplished… which is a pitty.

It would be incredibly useful to allow the programmer decide which parts of the page will be reloaded.

4 Likes

Hello @GitHunter0,

This is currently being designed, and we would be grateful if you could provide us with examples of app/workflow you would like to design without too much challenges!

Have a nice day,
Fanilo

4 Likes

Hey @andfanilo ,

I’m really glad you are working on that. Streamlit has a bright future.

For example:
I tried to design an app that a part of it requires a password to access. However, with every new user input value, the page is reloaded and the password is asked again.

Thank you, and keep the great work

1 Like

:+1: great !

In the meantime, you could check the st.forms method (blog post) to prevent page reloading on every user input, using instead a submit button to run the script login. Though you would still need to save that you are connected inside the unofficial SessionState.

:balloon: Fanilo

1 Like

Cool @andfanilo , I was precisely using st.forms (great feature by the way), but not SessionState. Once it becomes robust and official, it will definitively put Streamlit on another level.

Thank you for the feedback

1 Like

if it’s not too late for answer.
you can try this

  1. When the user enter name / password and presses submit button
  2. You can run a check to see if they are correct or not.
  3. If the credentials are correct create a session variable .
  4. if you want a logout button. Create a logout button which will delete the session variable.
  5. So in whatever part you want to display only if the user is logged in you can check if the session variable is present or not. if present display that content.
  6. or else show an error msg saying "please log in "

Hello @andfanilo,
Do you have any update on this new feature? Is it expected to be released during the next few months?

Thanks

Did you have a look at Streamlit Forms: Batch Input Widgets | Introducing Submit Button & Forms (streamlit.io) ?

There are also Streamlit Callbacks Store Information Across App Interactions | Session State (streamlit.io) which you can use to run a method on button click before rerunning the whole script.

Using forms, callbacks and Session State trickstery, you should be able to “mostly” manipulate the parts of code to run on button click.

Have a nice day,
Fanilo

I already had a look at the forms and it’s not what I want, although the feature is great
But yes the streamlit session state is exactly what I need, thanks a lot, it works perfectly and is as easy to use as the other features! Thanks for everything, Streamlit is really amazing :slight_smile:

Have a nice day too,
Quentin

1 Like

Hi ,
I see it’s a common post in the community forum. So here’s few workarounds I jotted down in this Blog Post or you can find similar content on this detailed video. Hope it helps.

Best
Avra

Hi, I have a similar problem. my code looks like this:

import streamlit as st

def heavy_calculations():
    # do some slow calculation

data = heavy_calculations()

st.write('## before filters')
st.dataframe(data)
col1, col2= st.columns(2)
upper_filter = col1.number_input("upper threshold")
lower_upper = col2.number_input("lower threshold")

# some filtration and styling

st.write('## after filters')
st.dataframe(data)

I need a solution to not reload the page on each filters choice and instead only apply them.
I don’t want to use cahing

1 Like

Having similar issues. It spoils the user experience. I ve used caching but it doesn’t seem to help much.

2 Likes

Hey all!

Just wanted to give a quick update since this post gets a ton of views. We are not working on a feature to prevent reruns at the moment. It’s something that touches on the fundamentals of Streamlit so we’ll need to think it through carefully. This takes time and we are currently focusing on other features.

Some workarounds (forms, caching, session state) were already posted above. These should solve most use cases!

I opened a feature request on Github for this topic. If you have use cases, please post them there and upvote with :+1:. This helps us prioritize and figure out how to best tackle this problem. We try to have all feature requests on Github, so we don’t need to comb through thousands of posts on the forum for planning.

Cheers,
Johannes

3 Likes

I am working on an application that needs user inputs and based on that inputs creates graphs. But, yes, using a submit button from a form or sliders, the reload makes me loose all the data frames and previous work done.
I applied a workaround by Avra:

with a checkbox. Yep, it is not perfect for my design or UX, but the thing works now. The user can change parameters and have new graphs.

3 Likes

I have a problem with my app; My app generates graphs, I can change the parameters that generate the graph. Those parameters I have in a selectbox and in a checkbox but every time I change them, the app restarts and stops showing the previous graph returning to the top of the page.
This is what the parameters look like:

Streamlit reruns with every interaction by design. It won’t behave like a terminal where things you write get added with each rerun; it will just start from scratch and run (with a memory of how you’ve changed the widgets).

If you share enough code to show the whole picture, I’m sure you can get additional direction.

This is the code: