Running and Deploying a Shiny for Python Application
June 16, 2023
Creating and deploying a dashboard may seem like a straightforward process. However, when I embarked on developing my first Shiny for Python app, I quickly encountered unexpected challenges. The limited online resources and guidance made the experience even more daunting. However, the satisfaction of successfully deploying the app motivated me to share my experience and offer guidance to others, helping them avoid the struggles I faced.
Running a Shiny for Python App
Shiny applications are typically run using a .py file, while most data science tasks are performed in Jupyter notebooks (.ipynb).
Converting a Jupyter Notebook to a Python Script
To bridge this gap, you need to generate a .py file from your Jupyter notebook. Follow these steps:
Open your .ipynb file in Jupyter Notebook.
Under the File tab, look for Jupytext (install it if necessary).
Select "Pair Notebook with Light Script."
This action creates a .py file from your notebook, which automatically syncs any changes made to the notebook.
Running the Application in a Terminal
To launch your Shiny for Python app, follow these steps:
Open a terminal (JupyterLab provides a built-in terminal).
Navigate to the folder where your .py file is located using the cd command.
Run the following command:
shiny run --reload app.py
shiny run app.py starts the application.
The --reload argument enables automatic reloading whenever code changes occur.
Once the command executes, you will receive a Uvicorn URL (e.g., http://127.0.0.1:8000), which you can open in your browser to view your app.
Deploying the Application
To make your app accessible online, deploy it using shinyapps.io. Follow these steps:
1. Install rsconnect
In your terminal, install the required package:
pip install rsconnect-python
2. Configure rsconnect
Create a shinyapps.io account (shinyapps.io).
Navigate to the Tokens section to generate an authentication token.
Configure rsconnect with your token:
rsconnect add --name <your-app-name> --token <your-token>
3. Generate a Manifest File
Run the following command to create a deployment manifest file:
rsconnect write-manifest app.py
4. Deploy Your App
Deploy your app using:
rsconnect deploy shiny --entrypoint app.py
Ensure that your working directory contains only one .py file, which will act as the entry point for deployment.
Common Deployment Errors and Solutions
1. Unwanted Checkpoints in the Working Directory
Each time you save, Jupyter creates checkpoint files, which can interfere with deployment. Either disable them or manually delete them before deployment.
2. "The Application Failed to Start" Error
This issue often arises due to missing package installations. Check your application logs on shinyapps.io to identify the specific missing packages and install them.
To view logs:
rsconnect logs --name <your-app-name>