♻️ Async Load
Submitted by Joshua Carroll
Summary
Decorator to run a function in the background, and update the app on completion.
Functions
async_load
Decorator to run a function in the background, and update the app on completion.
When you call a function decorated with @async_load()
, it will initially
return None
while the function executes asynchronously. A fragment will
periodically execute to check when the function completes.
Once the function completes, the app will do a full rerun, and this time the function will return whatever return value or raise an error. The return value is stored in session state and re-used on any subsequent reruns.
Similar to st.cache_data, calling the function repeatedly with different arguments or key will result in separate background threads and return values. The same arguments + key will always be treated as the same run / thread.
If you set refresh_every=
, the function is automatically rerun async on the
specified interval, and the return value is updated on complete.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
func |
Callable
|
The function to load in the background. |
required |
poll_interval |
float
|
How often to check if the function completed once it starts running. |
0.5
|
key |
str
|
A key to store the return value in session_state. |
None
|
refresh_every |
int
|
If set, the function will be re-executed and return value refreshed at the specified interval. This is based on the start time, not the end time (so it should refresh every interval, not every exec_time + interval) |
None
|
Source code in src/streamlit_extras/async_load/__init__.py
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 |
|
Import:
- You should add this to the top of your .py file
Examples
example
def example():
import time
import numpy as np
import pandas as pd
hide_running_man()
"`refresh_data()` runs in the background, so these widgets remain fully interactive"
st.button("Button 1")
st.slider("Random slider", 0, 100)
@async_load(refresh_every=4)
def refresh_data(x=1, sleep=2):
time.sleep(sleep)
return pd.DataFrame(
np.random.randn(5, 5) * x, columns=["a", "b", "c", "d", "e"]
)
df = refresh_data()
if df is not None:
"The dataframe updates every few seconds"
st.dataframe(df)
else:
"Show a skeleton while initial load runs async"
st._main._skeleton()