St.download button replace by st.button

Hi There,
If i using python, and i run this code, i can get new file with name "howtodownload.pdf)

import requests

URL = "https://www.codingem.com/python-download-file-from-url/"
response = requests.get(URL)
open("howtodownload.pdf", "wb").write(response.content)

NOW, my problem, i want to make st.button, when st. button clicked can download my url and then do some code.

saveto_gsheet=st.button("Save to Google Sheet")
if saveto_gsheet:
import requests
URL = "https://www.codingem.com/python-download-file-from-url/"
response = requests.get(URL)
open("instagram.pdf", "wb").write(response.content)
(and then some code to save to google sheet)

With this code, when i click button โ€œSave to Google Sheetโ€, i canโ€™t get my file (that code isnโ€™t download my file). Why ?

If i not using st. button i can get that file, now if i using st.button i canโ€™t get that file. thanks before

You can try a callback function instead and encapsulate your saving to sheet in the function, then use the on_click parameter for the button to call the function.

It seems like itโ€™s working fine. Here I saved it to a text file instead of a pdf:

from pathlib import Path

import requests
import streamlit as st

saveto_gsheet = st.button("Save to Google Sheet")
if saveto_gsheet:
    URL = "https://www.codingem.com/python-download-file-from-url/"
    response = requests.get(URL)
    open("instagram.txt", "w").write(response.text)
    st.write("Saved!")
    # (and then some code to save to google sheet)

st.write("Contents of instagram.txt:")

p = Path("instagram.txt")

if p.exists():
    st.code(p.read_text())

else:
    st.write("Not found!")

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