Introduction
Shinylive for Python lets you run interactive Shiny apps written in Python directly in your web browser—without needing a dedicated server. In this tutorial, you’ll build a simple Shiny for Python app that displays an interactive histogram. Then, you’ll export the app as a Shinylive application, turning your dynamic code into a set of static files that can be deployed anywhere.
1. Building Your Shiny App
We’ll create a basic Shiny for Python app using the new shiny
package for Python. This example uses a slider to control the number of bins in a histogram of random data.
Source
```{python}
from shiny import App, ui, render
import numpy as np
import matplotlib.pyplot as plt
# Define the user interface
app_ui = ui.page_fluid(
ui.input_slider("bins", "Number of bins:", 5, 30, 10, step=1),
ui.output_plot("histPlot")
)
# Define the server logic
def server(input, output, session):
@output
@render.plot
def histPlot():
# Generate random data
x = np.random.normal(0, 1, 1000)
# Create bin edges based on the slider value
bins = np.linspace(x.min(), x.max(), input.bins() + 1)
plt.figure(figsize=(8, 4))
plt.hist(x, bins=bins, color="skyblue", edgecolor="white")
plt.title("Interactive Histogram of Random Data")
plt.xlabel("Value")
plt.ylabel("Frequency")
plt.show()
# Create the Shiny app
app = App(app_ui, server)
```
Run the code block to test your interactive Shiny for Python app locally. You should see a slider and a histogram that updates based on the slider’s value.
Output
#| '!! shinylive warning !!': |
#| shinylive does not work in self-contained HTML documents.
#| Please set `embed-resources: false` in your metadata.
#| standalone: true
#| viewerHeight: 650
from shiny import App, ui, render
import numpy as np
import matplotlib.pyplot as plt
# Define the user interface
app_ui = ui.page_fluid(
ui.input_slider("bins", "Number of bins:", 5, 30, 10, step=1),
ui.output_plot("histPlot")
)
# Define the server logic
def server(input, output, session):
@output
@render.plot
def histPlot():
# Generate random data
x = np.random.normal(0, 1, 1000)
# Create bin edges based on the slider value
bins = np.linspace(x.min(), x.max(), input.bins() + 1)
plt.figure(figsize=(8, 4))
plt.hist(x, bins=bins, color="skyblue", edgecolor="white")
plt.title("Interactive Histogram of Random Data")
plt.xlabel("Value")
plt.ylabel("Frequency")
plt.show()
# Create the Shiny app
app = App(app_ui, server)
2. Exporting Your Application with Shinylive
Once your Shiny app works locally, you can export it as a Shinylive application. This converts your Python code into a set of static files (HTML, JavaScript, CSS, and WASM) that run entirely in the browser.
Steps to Export:
Organize Your App Files:
Save your app code (for example, in a file namedapp.py
) within a dedicated folder (e.g.,myapp
).Export the App:
Use the shinylive Python package from the command line to export your app:shinylive export myapp site
This command creates a new folder named
site/
that contains all the static files needed to run your app.Preview the Exported App Locally:
Launch a local static server (using a tool likehttp.server
in Python or any static file server) to preview your exported app. For example:python3 -m http.server --directory site --bind localhost 8008
Open your browser to the URL provided to see your serverless app in action.
3. Deploying to Static Hosting Services
After verifying that your exported app works locally, deploy the contents of the site/
folder to a static hosting service.
Here are the general steps for deploying your Shinylive app on GitHub Pages:
Create a Repository:
Initialize a GitHub repository and add thesite/
folder to it.Configure GitHub Pages:
In your repository settings, enable GitHub Pages and select the branch/folder containing your exported app (e.g., the root of the repository or adocs/
folder).Push and Publish:
Commit and push your changes. Your app should be accessible via the GitHub Pages URL provided in the repository settings.Access Your App:
Once GitHub Pages is enabled, your app will be accessible via a URL likehttps://yourusername.github.io/your-repo/
.
Other static hosting options like Netlify
follow similar steps: simply upload the contents of the site/
folder and configure the deployment settings.
4. Tips and Best Practices
Asset Management:
Check asset versions using the appropriate shinylive commands. If needed, update assets to ensure compatibility.Organizing Multiple Apps:
If exporting multiple apps, use subdirectories to keep each app separate and maintain shared asset consistency.Local Testing:
Always preview your exported application locally before deploying it to a static hosting service like GitHub Pages or Netlify.Code Readability:
Write modular, well-documented code to make future customizations easier.
Further Reading
- Introduction to Shinylive for Python
Get an overview of Shinylive for Python, its components, and its benefits. - Installing and Setting Up Shinylive for Python
Learn how to install the shinylive Python package and configure asset management. - Embedding Shinylive Python Apps in Quarto Documents
Discover how to embed Shinylive apps directly into your Quarto documents. - Advanced Customization and Troubleshooting for Shinylive (Python)
Explore advanced techniques for customizing and troubleshooting your Shinylive applications.
Conclusion
You’ve now built a basic interactive Shiny for Python application and learned how to export it as a Shinylive app. This serverless approach lets you deploy your interactive Python apps as static websites that run entirely in the browser. Experiment with further customizations, and explore the additional resources to deepen your understanding of Shinylive for Python.
References
Explore More Articles
Here are more articles from the same category to help you dive deeper into the topic.
Reuse
Citation
@online{kassambara2025,
author = {Kassambara, Alboukadel},
title = {Creating a {Basic} {Shinylive} {Python} {Application}},
date = {2025-03-20},
url = {https://www.datanovia.com/learn/interactive/python/shinylive/basic-app.html},
langid = {en}
}