MAC
MAC

Reputation: 1523

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

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? << https://discuss.streamlit.io/t/download-button-reloads-app-and-results-output-is-gone/17120>>

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.

Upvotes: 0

Views: 404

Answers (1)

Julia
Julia

Reputation: 66

You can use st.session_state.
I cannot recreate your example as exemplary data is missing, but you can stock the loaded data in the session state, and add other if/else statements to check if the respective session state is empty. If not, you can show the download buttons - this avoids them from disappearing.

Upvotes: 0

Related Questions