Jupyter compatibility

from httpx import get, AsyncClient

Helper functions


source

nb_serve

 nb_serve (app, log_level='error', port=8000, **kwargs)

Start a Jupyter compatible uvicorn server with ASGI app on port with log_level


source

nb_serve_async

 nb_serve_async (app, log_level='error', port=8000, **kwargs)

Async version of nb_serve


source

is_port_free

 is_port_free (port, host='localhost')

Check if port is free on host


source

wait_port_free

 wait_port_free (port, host='localhost', max_wait=3)

Wait for port to be free on host

Using FastHTML in Jupyter


source

JupyUvi

 JupyUvi (app, log_level='error', port=8000, start=True, **kwargs)

Start and stop a Jupyter compatible uvicorn server with ASGI app on port with log_level

Creating an object of this class also starts the Uvicorn server. It runs in a separate thread, so you can use normal HTTP client functions in a notebook.

app = FastHTML()

@app.route
def index(): return 'hi'

port = 8000
server = JupyUvi(app, port=port)
get(f'http://localhost:{port}').text
'hi'

You can stop the server, modify routes, and start the server again without restarting the notebook or recreating the server or application.

server.stop()

source

FastJupy

 FastJupy (hdrs=None, middleware=None, **kwargs)

Same as FastHTML, but with Jupyter compatible middleware and headers added

Instead of using the FastHTML class, use the FastJupy class. It’s a thin wrapper for FastHTML which adds the necessary headers and middleware required for Jupyter compatibility.

app = FastJupy()
rt = app.route
server = JupyUvi(app, port=port)

source

HTMX

 HTMX (path='', host='localhost', port=8000, iframe_height='auto')

An iframe which displays the HTMX application in a notebook.

@rt
def index():
    return Div(
        P(A('Click me', hx_get=update, hx_target='#result')),
        P(A('No me!', hx_get=update, hx_target='#result')),
        Div(id='result'))

@rt
def update(): return Div(P('Hi!'),P('There!'))
# Run the notebook locally to see the HTMX iframe in action
# HTMX()

# If only part of the page gets displayed, try tweaking the iframe_height parameter, for example:
# HTMX(iframe_height="800px")
server.stop()

jupy_app


source

jupy_app

 jupy_app (pico=False, hdrs=None, middleware=None, **kwargs)

Same as fast_app but for Jupyter notebooks

app,rt = jupy_app()
server = JupyUvi(app)
@rt
def index():
    return Div(
        P(A('Click me', hx_get=update, hx_target='#result')),
        P(A('No me!', hx_get=update, hx_target='#result')),
        Div(id='result'))

@rt
def update(): return Div(P('Hi!'),P('Rachel!'))
# Run the notebook locally to see the HTMX iframe in action
# HTMX()
# HTMX(update)
# HTMX('/update')
server.stop()