from fasthtml.common import *
from fasthtml.jupyter import JupyUvi, HTMX
Using Jupyter to write FastHTML
Writing FastHTML applications in Jupyter notebooks requires a slightly different process than normal Python applications.
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.
Let’s create an app with fast_app
.
= fast_app(pico=True) app, rt
Define a route to test the application.
@rt
def index():
return Titled('Hello, Jupyter',
'Welcome to the FastHTML + Jupyter example'),
P('Click', hx_get='/click', hx_target='#dest'),
Button(id='dest')
Div( )
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.
= JupyUvi(app) server
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 or leave it blank to use the default (8000).
# 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!')
Full screen view
You can view your app outside of Jupyter by going to localhost:PORT
, where PORT
is usually the default 8000, so in most cases just click this link.
Graceful shutdowns
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 specify a different port number in JupyUvi and HTMX with the port
parameter.
Cleaner solutions to the dangling thread are to kill the dangling thread (dependant on each operating system) or restart the computer.
server.stop()