-
-
Notifications
You must be signed in to change notification settings - Fork 63
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Rewrite the charts.audio example to load the external resource with a…
…sync pyodide.http.pyfetch() since stlite now supports top-level await
- Loading branch information
Showing
1 changed file
with
14 additions
and
5 deletions.
There are no files selected for viewing
19 changes: 14 additions & 5 deletions
19
packages/sharing-editor/public/samples/011_component_gallery/pages/charts.audio.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,16 +1,25 @@ | ||
import requests | ||
import streamlit as st | ||
import pyodide.http | ||
|
||
|
||
@st.cache_data | ||
def read_file_from_url(url): | ||
async def read_file_from_url(url): | ||
# st.cache_data does not work on async functions, | ||
# so we cache the data manually in st.session_state. | ||
cache_key = f"audio_data_{url}" | ||
if cache_key in st.session_state: | ||
return st.session_state[cache_key] | ||
|
||
headers = { | ||
"User-Agent": "StreamlitDocs/1.5.0 (https://docs.streamlit.io; [email protected])" | ||
} | ||
return requests.get(url, headers=headers).content | ||
res = await pyodide.http.pyfetch(url, headers=headers) | ||
data = await res.bytes() | ||
st.session_state[cache_key] = data | ||
return data | ||
|
||
|
||
file_bytes = read_file_from_url( | ||
# stlite supports top-level await. | ||
file_bytes = await read_file_from_url( | ||
"https://upload.wikimedia.org/wikipedia/commons/c/c4/Muriel-Nguyen-Xuan-Chopin-valse-opus64-1.ogg" | ||
) | ||
|
||
|