Hi,
I am currently working on a POC where I am trying to create a button that, when clicked, will trigger some data processing and then automatically download a CSV file to the user’s Downloads. However, I am facing a challenge in making this functionality work as intended.
Here is a code snippet that illustrates my current approach:
download_report = st.sidebar.button("Download Diagnosis Report")
if download_report:
conversation = format_to_conversation(conv_data)
diagnosis_report = get_summary(conversation)
data = {'Conversation': [conversation],
'Diagnosis Report': [diagnosis_report]}
df = pd.DataFrame(data)
csv = df.to_csv().encode('utf-8')
datetime_stamp = f"{datetime.now().strftime('%Y-%m-%d-%H-%M-%S')}"
st.download_button(
label="Download data as CSV",
data=csv,
file_name=f'diagnosis_report_{datetime_stamp}.csv',
mime='text/csv',
)
As you can see, st.download_button renders a new button for downloading the CSV file. However, my goal is to perform the download when the download_report button is clicked, without the need for an additional button click.
I would greatly appreciate any guidance or suggestions on how to achieve this functionality
Yes certainly, you can proceed to use only the second instance of the st.download_button instead of nesting this inside the st.sidebar.download_button (thus delete this first instance).
Sorry, there was a mistake in the code snippet i provided, i have edited the code. I want to perform some processing as well as download the csv file on click of download_report button. Is there a way to achieve thta?
The st.download_button would perform 1 thing which is to download the provided file. However, if you’d like it to do some pre-processing (like generating the report) followed by downloading the report, then you’ll need a custom button.
Please see this previous post with example code snippet that you can customize for your use case: