Summary: To create an interactive web application in a Jupyter Notebook, use the three libraries ipywidgets
, voila
, and binder
. This requires only basic Python programming skills without the need to learn a new framework.
There are various Python tools available to create web applications and frontend GUIs. For example, Flask and Django. As useful as they are, we still need to invest time in learning new frameworks. That might not be the highest on our priority list when we have spent a lot of time doing our Python project.
Is there a way to create a simple, interactive web application with basic Python skills? The answer is yes, and this article will show you exactly that in five steps.
💡 Your PDF Certificate: If you want to get a PDF certificate for completing this small course — e.g., to show to your employer or freelancing clients — feel free to check this out as a course on the Finxter Academy! 👈
We will first create some interactive widgets using ipywidgets in a Jupyter notebook. Then, we will render the notebook as a web application using Voilà. We will push the project onto a GitHub repository, and finally, host the web app on Binder.
Let’s get started! 💪
Step One: Create A New Git Repository and Install Python Packages
It is unnecessary to push every coding project onto our Git repository. But we need a Git repo for this project. That is because Binder will refer to it to create a Docker container that hosts our web application. For this tutorial, I have created a GitHub repo named jupyter_webapp_demo
. Feel free to clone it at https://github.com/finxter/jupyter_webapp_demo.
To clone a Git repo onto your local directory, type the following command on a terminal or command prompt:
$ git clone https://github.com/username/project_name.git
Next, we are going to create a virtual environment for the code project. It is always a good practice to isolate the required dependencies per project. We will export the names and versions of all installed packages to a text file later as a requisite for Binder.
To create and activate a virtual environment, type the following commands:
$ python3 -m venv venv_name $ cd venv_name\Scripts $ activate $ cd ..\..
Figure 1: Clone a Git repository and activate a virtual environment.
Install the Jupyter Notebook app using either the conda or the pip package manager:
$ conda install -c conda-forge notebook
or
$ pip install notebook
Type the following command to open the Jupyter Notebook app:
$ jupyter notebook
You will see it opened on your default web browser.
Now, create a new Python 3 notebook. Install three modules named widgetsnbextension, ipywidgets, and voila, as follows:
$ pip install widgetsnbextension $ pip install ipywidgets $ pip install voila
We need to enable the extensions to be properly displayed on the notebook:
!jupyter nbextension enable --py widgetsnbextension --sys-prefix !jupyter serverextension enable voila --sys-prefix
Comment out the commands and execute the cell again. That will hide the displayed text from the previous cell execution from our web app.
#!jupyter nbextension enable --py widgetsnbextension --sys-prefix #!jupyter serverextension enable voila --sys-prefix
Now we are good to go. Time to load the web app with some sliders and buttons.
Step Two: Create Interactive Web Elements with Ipywidgets
Ipywidgets is a module that lets us create interactive widgets in Jupyter notebooks. For example, buttons, text boxes, sliders, progress bars, and more. Feel free to explore the widget list [1] and use any that would help in showcasing your code project.
Now, let’s create some widgets that curate a text message to Grandma for a dinner appointment.
Figure 2: A web app that books a dinner appointment with Grandma.
For that, we will need widgets for displaying an image, a toggle button, a date picker, an integer slider, and a button. We will go through this tutorial for all the widgets but not for the layout. Feel free to refer to the given Git repo to see the complete notebook.
First, import the ipywidgets module and the IPython display function:
import ipywidgets as widgets from IPython.display import display, clear_output
The code for all widgets follows a similar and consistent format. Take the code for a toggle button as an example:
grand = widgets.ToggleButtons( options=['grandson', 'granddaughter'] )
The ToggleButtons
function from the widgets module is called. Its options parameter is filled with some button names that we want. For this, two toggle buttons are created: grandson and granddaughter. This function is passed to a variable named grand.
The following examples show how straight-forward it is to create any widget:
- A text box
name = widgets.Text(placeholder='Your name here')
- A date picker
date = widgets.DatePicker(description='Pick a Date')
- An integer slider
friends = widgets.IntSlider( value=3, min=0, max=10, step=1, style={'description_width': 'initial' )
We need to create an extra function to configure the actions to be performed when the button is pressed:
button_send = widgets.Button( description='Send to grandma', tooltip='Send', style={'description_width': 'initial'} ) output = widgets.Output() def on_button_clicked(event): with output: clear_output() print("Sent message: ") print(f"Dear Grandma! This is your favourite {grand.value}, {name.value}.") print(f"I would love to come over on {date.value} for dinner, if that's okay for you!") print(f"Also, if you don't mind, I'll bring along {friends.value} hungry ghosts for your delicious food!") button_send.on_click(on_button_clicked) vbox_result = widgets.VBox([button_send, output])
Notice how literal it is to get the information from all widgets:
grand.value name.value date.value friends.value
Done? Then we are ready to turn the notebook into a web application.
Step Three: Render the Notebook as A Web Application using Voilà
As we have installed the Voilà package, we can now see the button appeared on our notebook interface.
Figure 3: A Voilà button that renders a notebook as a web application.
There are two ways to debug the notebook as a web application before we host it somewhere else. Either press the Voilà button or execute the notebook from the terminal as follows:
$ voila notebook_name.ipynb
When any of them is executed, a new tab will appear on our default web browser. It shows how our web application looks like in the local directory. Take your time to edit and complete your web app.
Step Four: Push the Code Project onto Your Git Repository
Next, we need to create a requirements text file for the web app. To do that, type the following command in your activated virtual environment:
$ pip freeze > requirements.txt
The file includes all packages that you have installed in the current virtualenv. Remove the following lines from the file as they are incompatible with Binder:
pywin32==300 terminado==0.9.2
We are now ready to commit and push our project folder onto our Git repo by typing the following commands:
$ git add notebook.ipynb $ git add requirements.txt $ git commit -m “commit message” $ git push origin branch_name
Notice the changes taking place on our Git repo.
Step Five: Host the Web Application on Binder
Now, we want the notebook to be displayed as a web app that is hosted on Binder, which anyone can access with a URL. Go to mybinder.org and choose the appropriate configurations for the code project.
Figure 4: A sample configuration for hosting a Git project on Binder.
Elaboration for Figure 4:
- Choose your Git hosting platform, such as GitHub, GitLab, etc.
- Insert the URL of your Git repo.
- Insert the name of your notebook after
'/voila/render/'
. - Choose URL instead of File.
- Click the Launch button.
- Copy the text for displaying the Binder badge and paste it on the README file. Your web app will be shown when the badge is clicked on the Git repo.
And… voilà! Now you have a simple web application to showcase your work.
Conclusion
This article explains how to create a web application in a Jupyter notebook. It only needs basic Python programming knowledge. The ipywidgets module is used to create interactive widgets. The voilà module is used to render the notebook as a web application. The web app is hosted on Binder, which is accessible by a URL.
Programmer Humor
There are only 10 kinds of people in this world: those who know binary and those who don’t.
👩🧔♂️
~~~
There are 10 types of people in the world. Those who understand trinary, those who don’t, and those who mistake it for binary.
👩🧔♂️👱♀️
Reference: [1] https://ipywidgets.readthedocs.io/en/stable/examples/Widget%20List.html
More Projects and Learnings on the Finxter Academy! 👇
Do you want to keep doing real things with your coding skills rather than working on toy projects forever?
If yes, feel free to check out our full course on this subject — and many more similar coding projects for real value creation on the Finxter Academy: