I have a streamlit app that download automatically one file at the end of each loop iteration. The problem is that at the end of each iteration, the code also adds a few empty spaces. I tried to remove the spaces, but it did not work. Can someone maybe help, please?
href = f'''
<html>
<body>
<a id="dl" style="display:none;" download="{code}_Zeitreihe.zip"
href="data:application/zip;base64,{b64}"></a>
<script>document.getElementById("dl").click();</script>
</body>
</html>
'''
# Inject auto-download HTML
st.components.v1.html(href, height=0, width=0)

This is unfortunately expected. To work around it, you could use an empty to replace the script instead of append it each time. Alternatively, you could use a fragment which would automatically replace itself by default.
In addition to either solution, you could also use containers to make sure the script is always at the end of the page.
Note: You’d just need to make sure at least one character was different in what you were injecting so that the script will execute. If you don’t have something about the script that changes with each iteration, include a timestamp comment, for example.
import streamlit as st
from streamlit.components.v1 import html
from datetime import datetime
if "run_every" not in st.session_state:
st.session_state.run_every = 0
@st.fragment(run_every=1)
def run_script():
script = f"<p>Inject some script {datetime.now()}</p> "
html(script)
body = st.container()
footer = st.container()
if body.button("Start"):
with footer:
run_script()
with body:
st.button("Stop")
"Whatever comes after"
Thank you for the reply! The app run in streamlit 1.28 which does not include the st.fragment. Do you know peharps another workaround this?
Is it possible to add the spaces to a st.expander?
Use footer=st.empty()
and write your script to the footer. This will replace the script text instead of append it.
Yup! You can incject your script in any container you want, including an expander.