Best practice for real-time app

Hi everyone,

My idea is to develop an app that takes data from mongoDB database. It will pull out from the MongoDB data at every fixed time-step (so far I have fixed every 5 min). Then, I will turn into dataframes, perform some calculations and plot some results. The idea is to present both accomolative results and results related to the real-time data. I would to know if anyone has an example code (with similar characteristics), or recommend best packages to execute that - packages like to plot real-time data.

The ‘Plotting’ demo from streamlit hello does something similar to what you are describing:

import time
import numpy as np

progress_bar = st.sidebar.progress(0)
status_text = st.sidebar.empty()
last_rows = np.random.randn(1, 1)
chart = st.line_chart(last_rows)

for i in range(1, 101):
    new_rows = last_rows[-1, :] + np.random.randn(5, 1).cumsum(axis=0)
    status_text.text("%i%% Complete" % i)
    chart.add_rows(new_rows)
    progress_bar.progress(i)
    last_rows = new_rows
    time.sleep(0.05)

progress_bar.empty()

# Streamlit widgets automatically run the script from top to bottom. Since
# this button is not connected to any other logic, it just causes a plain
# rerun.
st.button("Re-run")

The key line is chart.add_rows(new_rows), which appends data frame rows to a chart object. When you do this, the app knows that an input has changed and re-renders the graph appropriately.

2 Likes

Awesome!

1 Like

Using this method, the rest of the code won’t get executed until the end of the for loop.
Is there a way to run the loop in the “background” while letting the rest of the code run? Is there where the “async” technique comes into handle?
Thanks.