Stlite: In-browser Streamlit Serverless Streamlit Running Entirely in Your Browser This project is tested with BrowserStack. Streamlit is a Python web app framework for the fast development of data apps. This project is to make it run completely on web browsers with the power of Pyodide, WebAssembly (Wasm)-ported Python. Try it out online (Stlite Sharing) Visit Stlite Sharing. Create a desktop app (@stlite/desktop)…
Serverless Streamlit Running Entirely in Your Browser
This project is tested with BrowserStack.
Streamlit is a Python web app framework for the fast development of data apps. This project is to make it run completely on web browsers with the power of Pyodide, WebAssembly (Wasm)-ported Python.
Since 0.76.0, @stlite/mountable is renamed to @stlite/browser, and the API is changed. See the Migration guide for the details.
You can use Stlite on your web page loading the script and CSS files via <script> and <link> tags as below.
Here is a sample HTML file.
<!doctypehtml><html><head><metacharset="UTF-8"/><metahttp-equiv="X-UA-Compatible"content="IE=edge"/><metaname="viewport"content="width=device-width, initial-scale=1, shrink-to-fit=no"/><title>Stlite App</title><linkrel="stylesheet"href="https://cdn.jsdelivr.net/npm/@stlite/[email protected]/build/stlite.css"/><scripttype="module"src="https://cdn.jsdelivr.net/npm/@stlite/[email protected]/build/stlite.js"></script></head><body><streamlit-app>
import streamlit as st
name = st.text_input('Your name')
st.write("Hello,", name or "world")
</streamlit-app></body></html>
In this sample,
Stlite is set up by loading the JavaScript and CSS files via <script> and <link> tags.
The Stlite runtime recognizes the <streamlit-app> tag and launches the Streamlit app defined in it.
Stlite also provides the “more raw” API with which you call the mount() JavaScript function explicitly to mount a Streamlit app on a specific element in the DOM.
<!doctypehtml><html><head><metacharset="UTF-8"/><metahttp-equiv="X-UA-Compatible"content="IE=edge"/><metaname="viewport"content="width=device-width, initial-scale=1, shrink-to-fit=no"/><title>Stlite App</title><linkrel="stylesheet"href="https://cdn.jsdelivr.net/npm/@stlite/[email protected]/build/stlite.css"/></head><body><divid="root"></div><scripttype="module">import{ mount }from"https://cdn.jsdelivr.net/npm/@stlite/[email protected]/build/stlite.js";mount(`
import streamlit as st
name = st.text_input('Your name')
st.write("Hello,", name or "world")
`,
document.getElementById("root"),);</script></body></html>
In this sample,
Stlite’s mount() function is imported within the <script> tag. You also need to load the CSS file via <link> tag as well.
mount() mounts the Streamlit app on the <div id="root" /> element as specified via the second argument. The app script is passed via the first argument.
[!NOTE]
If you use backticks ` inside your Streamlit code (e.g. writing markdown with code blocks), they may conflict with JavaScript string literal’s backtick like st.mount(` ... `). To avoid it, you can escape them with with a preceding backslash \.
This issue doesn’t occur when you use the <streamlit-app> tag.
mount(`
import streamlit as st
st.markdown("This is an inline code format: \`code\`")
`,
document.getElementById("root"),);
Hint: Technically, the <streamlit-app> tag API is a wrapper around the mount() function.
More controls
If you need to do more such as
mounting multiple files
installing dependencies
setting the Streamlit config via the config.toml file
you can use the <streamlit-app> tag with the <app-file>, and <app-requirements> tags as below.
<streamlit-app><app-filename="streamlit_app.py"entrypoint>
import streamlit as st
import matplotlib.pyplot as plt
import numpy as np
size = st.slider("Sample size", 100, 1000)
arr = np.random.normal(1, 1, size=size)
fig, ax = plt.subplots()
ax.hist(arr, bins=20)
st.pyplot(fig)
</app-file><app-filename=".streamlit/config.toml">
[client]
toolbarMode = "viewer"
</app-file><app-requirements>
matplotlib
</app-requirements></streamlit-app>
If you want to use the mount() function instead, it would look like this:
mount({requirements:["matplotlib"],// Packages to installentrypoint:"streamlit_app.py",// The target file of the `streamlit run` commandfiles:{"streamlit_app.py":`
import streamlit as st
import matplotlib.pyplot as plt
import numpy as np
size = st.slider("Sample size", 100, 1000)
arr = np.random.normal(1, 1, size=size)
fig, ax = plt.subplots()
ax.hist(arr, bins=20)
st.pyplot(fig)
`,},streamlitConfig:{// Streamlit configuration"client.toolbarMode":"viewer",},},
document.getElementById("root"),);
Various ways to load files (files option)
You can pass an object to the files option to mount files onto the file system, whose keys are file paths, and you can specify the values in various ways as below. See also the File system section for more details.
Passing string or binary data
You can pass the file content as a string or binary data.
This is what we did in the example above.
mount({files:{"path/to/text_file.txt":"file content","path/to/binary_file.bin":newUint8Array([0x00,0x01,0x02,0x03]),},// ... other options ...},
document.getElementById("root"),);
Passing an object with a URL
You can use this way to load a file from a URL and mount it to the specified path on the virtual file system.
Either an absolute or relative URL is accepted. Consider as the same as the url option of the fetch() function.
mount({files:{"path/to/file":{url:"https://example.com/path/to/file",},"path/to/file2":{url:"./path/to/file",},},// ... other options ...},
document.getElementById("root"),);
mount({files:{"path/to/text_file.txt":{data:"file content",opts:{encoding:"utf8",},},"path/to/file":{url:"https://example.com/path/to/file",opts:{encoding:"utf8",},},},// ... other options ...},
document.getElementById("root"),);
Loading archive files (archives option)
You can load archive files such as zip files, unpack them, and mount the unpacked files to the file system by using the archives option.
The url field of each item accepts either an absolute or relative URL. Consider as the same as the url option of the fetch() function.
The downloaded archive file is unpacked by the pyodide.unpackArchive(buffer, format, options) function. You have to pass the rest of the arguments of the function, format and options as below.
mount({archives:[{url:"./foo.zip",// buffer: new Uint8Array([...archive file binary...]), // You can also pass the binary data directlyformat:"zip",options:{},},],// ... other options ...},
document.getElementById("root"),);
Multipage apps
You can pass the multiple files to the files option as below to construct the multipage app structure, the entry point file and pages/*.py files.
mount({entrypoint:"👋_Hello.py",files:{"👋_Hello.py":`
import streamlit as st
st.set_page_config(page_title="Hello")
st.title("Main page")
`,"pages/1_⭐️_Page1.py":`
import streamlit as st
st.set_page_config(page_title="Page1")
st.title("Page 1")
`,"pages/2_🎈_Page2.py":`
import streamlit as st
st.set_page_config(page_title="Page2")
st.title("Page 2")
`,},},
document.getElementById("root"),);
Customizing the Streamlit configuration (streamlitConfig option)
You can pass the Streamlit configuration options to the streamlitConfig field as key-value pairs as below. Unlike the original Streamlit configuration, the options are passed as a flat object with the keys separated by dots.
mount({streamlitConfig:{"theme.base":"dark","theme.primaryColor":"#00b4d8","theme.backgroundColor":"#03045e","theme.secondaryBackgroundColor":"#0077b6","theme.textColor":"#caf0f8","client.toolbarMode":"viewer","client.showErrorDetails":false,},// ... other options ...},
document.getElementById("root"),);
Install packages with options
Specifying the installs option on mount() or calling controller.install() allows you to install packages with specific options that are passed to micropip.install internally.
In the example above, the Stlite script is loaded from the versioned URL.
The following URLs are also available, while our recommendation is to use the versioned one as above because the API may change without backward compatibility in future releases.
This URL points to the head of the main branch which is usually ahead of the released packages.
However, we strongly recommend NOT to use this URL for production because this might be broken and there is no guarantee that this resource will be kept available in the future.
Different Pyodide distributions (pyodideUrl option)
Stlite uses Pyodide and loads it from the CDN by default. You can use your own Pyodide distribution by passing the URL to the pyodideUrl option as below. This would be helpful for example when your organization has a restrictive policy for CDN access.
mount({pyodideUrl:"https://<your-pyodide-distribution-url>/pyodide.js",// ... other options ...},
document.getElementById("root"),);
Pyodide provides two distribution types, full and core, and you should serve the full distribution in this case.
Stlite loads some packages from the Pyodide distribution such as micropip and they are not included in the core distribution.
Even with the full distribution whose size is quite large (+200MB), only the necessary packages are loaded on demand, so the actual size of loaded resources is smaller and you don’t have to choose the core distribution worrying about the size. Ref: #1007.
File system
Stlite executes your Python code on Pyodide in the browser, and Pyodide has its own Linux-like file system isolated from the host OS (see Pyodide’s or Emscripten’s documents about the FS for details).
The source code and data files are mounted on the file system through the files and archives options as described above, and the Python code can access them. So, for example, what open("path/to/file") reads or writes is the file on the file system virtually existing in the browser, not a file on the host OS.
The default file system (MEMFS) is ephemeral, so the files saved in the directories are lost when the page is reloaded.
The root / and some directories including home are mounted as MEMFS, the ephemeral file system, by default.
File persistence with IndexedDB backend
To persist the files across the app restarts, you can use the IndexedDB-based file system (IDBFS). The files saved in the directories mounted with IDBFS are stored in the browser’s IndexedDB, so they are persistent across the app restarts.
In the case of @stlite/browser, you can mount the IndexedDB-based file system, IDBFS to the specified directories in the virtual file system, by passing the idbfsMountpoints option as below.
The mounted file system is persistent across the page reloads and the browser sessions.
mount({idbfsMountpoints:["/mnt"],// Mount the IndexedDB-based file system to the /mnt directory.entrypoint:"streamlit_app.py",files:{"streamlit_app.py":`
import datetime
import streamlit as st
with open("/mnt/data.txt", "a") as f:
f.write(f"{datetime.datetime.now()}\\n")
with open("/mnt/data.txt", "r") as f:
st.code(f.read())
`,},// ... other options ...},
document.getElementById("root"),);
HTTP requests
To make HTTP requests, these libraries work on Stlite.
See also the following section about top-level await to know how to use the async method pyodide.http.pyfetch().
Stlite automatically enables koenvo/pyodide-http’s patches to make requests and urllib work,
while the networking libraries do not work in general on the Pyodide runtime (Python in browser) as written in this doc and Pyodide provides its standard alternative methods to make HTTP requests, pyodide.http.pyfetch() and pyodide.http.open_url().
Also, urllib3 supports Pyodide since 2.2.0 as this document says.
SharedWorker mode
Normally, each app created by stlite.mount() or <streamlit-app> runs in its own worker.
It brings good isolation but also can lead to huge memory consumption when there are many Stlite apps running at the same time.
In such a case, running the apps in a single worker can help mitigate the resource consumption, and Stlite provides SharedWorker mode to do it.
To enable SharedWorker mode, set shared-worker attribute on the <streamlit-app> tag
<streamlit-appshared-worker>
...
</streamlit-app>
or set the sharedWorker option to true on stlite.mount
stlite.mount({sharedWorker:true,// ... other options ...},
document.getElementById("root"));
The Python environment and file system are not isolated in the SharedWorker.
A different home directory is set for each app (/home/pyodide/<id>) but the files are still accessible from all the apps running in the worker.
Also modifications on the Python environment (e.g. installed packages or monkey-patching modules) are shared across all apps.
As Stlite runs on the web browser environment (Pyodide runtime), there are things not working well. The known issues follow.
st.spinner() does not work with blocking methods like pyodide.http.open_url() because Stlite runs on a single-threaded environment, so st.spinner() can’t execute its code to start showing the spinner during the blocking method occupies the only event loop.
If you want to show a spinner with a blocking method, add a 0.1-second sleep before the blocking method call, although this will definitely add an empty 0.1-second wait to the execution.
with st.spinner("Running a blocking method..."):
await asyncio.sleep(0.1) # Add this line to wait for the spinner to start showing
some_blocking_method()
st.bokeh_chart() does not work since Pyodide uses Bokeh version 3.x while Streamlit only supports 2.x. The 3.x support for Streamlit is tracked here: https://github.com/streamlit/streamlit/issues/5858
time.sleep() is no-op. Use asyncio.sleep() instead. This is a restriction from Pyodide runtime. See https://github.com/pyodide/pyodide/issues/2354. The following section about top-level await may also help to know how to use async functions on Stlite.
st.write_stream() should be used with an async generator function rather than a normal generator function. Due to the same reason as st.spinner() above, the normal generator function does not work well in the browser environment, while it still can be passed to st.write_stream(). The following is an example of st.write_stream() with an async generator function.
async def stream():
for i in range(10):
yield i
await asyncio.sleep(1)
st.write_stream(stream)
TL;DR: Use top-level await instead of asyncio.run() on Stlite.
Unlike the original Streamlit, Stlite supports top-level await due to the differences in their execution models. Streamlit runs in a standard Python environment, allowing the use of asyncio.run() when an async function needs to be executed within a script. In contrast, Stlite runs in a web browser, operating in an environment where the only event loop is always in a running state. This makes it impossible to use asyncio.run() within a script, necessitating the support for top-level await.
Top-level await can be useful in various situations.
Example 1: asyncio.sleep()
One of the most common use cases is asyncio.sleep(). As mentioned in the previous section, time.sleep() is no-op on Stlite because its blocking nature is not compatible with the single-threaded event loop in the web browser environment. Instead, asyncio.sleep(), which is non-blocking, can be used to pause the execution of a script for a specified amount of time.
You can use top-level await either for asyncio.sleep() directly or for an async function that contains asyncio.sleep() like the following:
import asyncio
import streamlit as st
st.write("Hello, world!")
await asyncio.sleep(3)
st.write("Goodbye, world!")
import asyncio
import streamlit as st
async def main():
st.write("Hello, world!")
await asyncio.sleep(3)
st.write("Goodbye, world!")
await main()
Example 2: pyodide.http.pyfetch()
Another common use case is accessing external resources. Pyodide provides a Python wrapper of browser’s Fetch API, pyodide.http.pyfetch() for making HTTP requests. Since this method is async, top-level await is sometimes used to handle the response.
评论