Using Jupyter to write FastHTML

To wrote FastHTML applications in Jupyter notebooks requires a slightly different process than normal Python applications.

Download this notebook and try it yourself

The source code for this page is a Jupyter notebook. That makes it easy to directly experiment with it. However, as this is working code that means we have to comment out a few things in order for the documentation to build.

The first step is to import necessary libraries. As using FastHTML inside a Jupyter notebook is a special case, it remains a special import.

from fasthtml.common import *
from fasthtml.jupyter import *

Let’s use jupy_app to instantiate app and rt objects. jupy_app is a thin wrapper around the fast_app function.

app, rt = jupy_app()

Define a route to test the application.

@rt
def index():
    return Titled('Hello, Jupyter',
           P('Welcome to the FastHTML + Jupyter example')
    )

Set the port in a variable so it can be more easily shared between the server and HTMX symbols described below.

port = 8000

Create a server object using JupyUvi, which also starts Uvicorn. The server runs in a separate thread from Jupyter, so it can use normal HTTP client functions in a notebook.

# Run locally, uncomment this line to create and start the server
# server = JupyUvi(app, port=port)

The HTMX callable displays the server’s HTMX application in an iframe which can be displayed by Jupyter notebook. Pass in the same port variable used in the JupyUvi callable above.

# Run locally, uncomment this line to display the HTMX application in Jupyter
# HTMX(port=port)

When you want to gracefully shut down the server use the server.stop() function displayed below. If you restart Jupyter without calling this line the thread may not be released and the HTMX callable above may throw errors. If that happens, a quick temporary fix is to change the port number above to something else.

Cleaner solutions to the dangling thread are to kill the dangling thread (dependant on each operating system) or restart the computer.

# Run locally, uncomment this line to stop the server
# server.stop()