4

I have to reload a Streamlit chart every 5 seconds, in order to visualize the new data in a XLSX report. How to achieve this?

import streamlit as st
import pandas as pd
import os

mainDir = os.path.dirname(__file__)
filePath = os.path.join(mainDir, "sources\\test.xlsx")
df = pd.read_excel(filePath)

option1 = 'Product'
option2 = 'Quantity'

df = df[[option1, option2]].set_index(option1)

st.write('Product Quantity')
st.area_chart(df)
Julio S.
  • 944
  • 1
  • 12
  • 26

1 Answers1

6

Streamlit recognizes every time your source code changes. So, based on this premise, one way to achieving this is to create an empty "dummy.py" file, which will be imported by the main script and updated every 5 seconds by another script running simultaneously:

  • create an empty "dummy.py" file inside the same folder of your main script;

  • create a script called "refresher.py" in the same folder;

    • now put the following While loop inside your "refresher.py" file, in order to update the "dummy.py" with a random number (commented) every 5 seconds:

      from random import randint
      import time
      import os
      
      def refresher(seconds):
          while True:
              mainDir = os.path.dirname(__file__)
              filePath = os.path.join(mainDir, 'dummy.py')
              with open(filePath, 'w') as f:
                  f.write(f'# {randint(0, 10000)}')
              time.sleep(seconds)
      
      refresher(5)
      
  • add the following line to the script with your Streamlit chart code: """   from dummy import *   """

  • run the "refresher.py" script;

  • run the Streamlit script with your chart;

  • Streamlit from now on will recognize any modifications in the "dummy.py file" as a modification in the source code;

  • Once the web page is fully loaded, it will alert you the source file was changed. Click on " Alway rerun" and that's it.

Julio S.
  • 944
  • 1
  • 12
  • 26
  • When I run this my streamlit app just spins and never loads - perhaps the updates broke this? – OrionTheHunter Aug 29 '20 at 00:57
  • @OrionTheHunter you probably missed the import """ from dummy import * """. It still works on the version 0.66.0 – Julio S. Sep 15 '20 at 17:17
  • It works on my local machine. But when I deployed it to prod, which receives 10k+ views a day, I just see the page loading. – user May 04 '21 at 23:32