Using Jupyter to write FastHTML

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

Writing 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(pico=True)

Define a route to test the application.

@rt
def index():
    return Titled('Hello, Jupyter',
           P('Welcome to the FastHTML + Jupyter example'),
           Button('Click', hx_get='/click', hx_target='#dest'),
           Div(id='dest')
    )

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.

server = JupyUvi(app)

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.

# This doesn't display in the docs - uncomment and run it to see it in action
# HTMX()

We didn’t define the /click route, but that’s fine - we can define (or change) it any time, and it’s dynamically inserted into the running app. No need to restart or reload anything!

@rt
def click(): return P('You clicked me!')

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.

server.stop()