下载按钮重新加载应用程序,结果输出消失,需要在 Streamlit 中重新运行

问题描述 投票:0回答:1

我使用下载按钮并使用它下载后,例如应用程序重新加载数据并且输出消失。 我们能否克服这个问题,以便在下载输出时保留并且应用程序不应该重新加载。

我也研究过这个,但不知道如何实现? << https://discuss.streamlit.io/t/download-button-reloads-app-and-results-output-is-gone/17120>>

我的代码:

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))

如果我单击

Download 1
,则输出消失,我无法
Download 2
,然后我需要再次单击“处理”按钮。

python-3.x frontend streamlit
1个回答
0
投票

您可以使用st.session_state
我无法重新创建您的示例,因为示例数据丢失,但您可以将加载的数据存储在会话状态中,并添加其他 if/else 语句来检查相应的会话状态是否为空。如果没有,您可以显示下载按钮 - 这可以避免它们消失。

© www.soinside.com 2019 - 2024. All rights reserved.