Download-Button reloads app and results output is gone and need to re-run

Hi,

I use the download button and after using it to download e.g. data the app reloads and the output is gone.
Can we overcome this so that when downloading the output remains and app should not reloads.

I also looked into this but not sure how to implement it? << Download-Button reloads app and results / output is gone>>

My code:

import streamlit as st
import pandas as pd
import requests
import json
from datetime import datetime, timedelta,date
import time

# Mock function api_1
@st.cache_data
def api_1(text):
    #calls some api_1 and returns response in DF
    df = pd.DataFrame({"text": text, "output1": answers})
    return df

# Mock function api_2
@st.cache_data
def api_2(text):
    #calls some api_2 and returns response in DF
    df = pd.DataFrame({"text": text, "output2": answers})
    return df


# Streamlit UI layout
st.set_page_config(page_title="DEMO UI", layout="wide")
st.title("DEMO UI")

# Side bar filters
st.sidebar.header("Filters")
text_input = st.sidebar.text_area("Enter text(s) (separated by line breaks)")
uploaded_file = st.sidebar.file_uploader("Upload CSV file with text", type=["csv"])
_name = st.sidebar.selectbox("Select Client Name", ["A", "B", "C"])
_experience = st.sidebar.selectbox("Select Experience", ["W", "A"])
_type = st.sidebar.selectbox("Select Type", ["p", "b"])
default_columns = ['.....','...']
cols=['.....','...','.....','...']
with st.sidebar:
    all_columns = st.multiselect("ChooseColumns", cols, default=default_columns)


# Button to trigger processing
if st.sidebar.button("Process"):
    try:
        if uploaded_file is not None:
            texts = uploaded_file.read().decode("utf-8-sig").split("\n")
        else:
            texts = text_input.split("\n")

        text = [text.strip() for text in texts if text.strip()]
        #to remove double quotes from string
        text=[u.replace('"', '') if (u.startswith('"') and u.endswith('"')) else u for u in text ]

        # Mock api_1
        _df1 = api_1(text)
        if _df1 is not None:
            # Display tables
            st.header("Response Tables")
            st.subheader("api_1")
            st.table(_df1)  # Set width=0 to use full width
            st.download_button(
                label="Download 1",
                data=_df1.to_csv(index=False, encoding="utf-8-sig"),
                file_name="file1.csv",
                key="key1"
            )

        # Mock api_2
        _df2=api_2(text)
        if _df2 is not None:
            # Display tables
            st.subheader("api_2")
            st.table(_df2)  # Set width=0 to use full width
            st.download_button(
                label="Download 2",
                data=_df2.to_csv(index=False, encoding="utf-8-sig"),
                file_name="file2.csv",
                key="key2"
            )

    except Exception as e:
        st.error("An error occurred: {}".format(e))

If I click on Download 1 then the output is gone and I cannot Download 2 and then I need to Click Process button again.

Any help @ kajarenc
@Caroline

Hi @piam

A solution is being implemented for the download button to not reload the app and is in the roadmap (https://roadmap.streamlit.app/#aug-oct-2023). In essence, the app logic in Streamlit reloads the app with every user interaction. To prevent this, one can use session state to store the interaction state.

Please refer to the relevant Docs page:

Hope this helps!

1 Like

Thank you @dataprofessor. This is awesome. Could you also please point me to exact line item in page https://roadmap.streamlit.app/#aug-oct-2023 which talks about download button to not reload the app is in the roadmap

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