from httpx import get, AsyncClientJupyter兼容性
在Jupyter笔记本中使用FastHTML
辅助函数
nb_服务
nb_serve (app, log_level='error', port=8000, host='0.0.0.0', **kwargs)
在 port 上启动一个与Jupyter兼容的uvicorn服务器,使用ASGI app 和 log_level
异步服务
nb_serve_async (app, log_level='error', port=8000, host='0.0.0.0', **kwargs)
nb_serve 的异步版本
端口是否空闲
is_port_free (port, host='localhost')
检查 host 上的 port 是否空闲
等待端口空闲
wait_port_free (port, host='localhost', max_wait=3)
等待 host 上的 port 可用
在Jupyter中使用FastHTML
显示
show (*s)
与 fasthtml.components.show 相同,但还添加了 htmx.process()
渲染_ft
render_ft ()
htmx配置端口
htmx_config_port (port=8000)
JupyUvi
JupyUvi (app, log_level='error', host='0.0.0.0', port=8000, start=True, **kwargs)
在port上启动和停止一个与Jupyter兼容的uvicorn服务器,使用ASGI app和log_level
创建此类的对象还会启动 Uvicorn 服务器。它在一个单独的线程中运行,因此您可以在笔记本中使用普通的 HTTP 客户端功能。
app = FastHTML()
rt = app.route
@app.route
def index(): return 'hi'
port = 8000
server = JupyUvi(app, port=port)get(f'http://localhost:{port}').text'hi'
您可以停止服务器,修改路由,然后再次启动服务器,而无需重新启动笔记本或重新创建服务器或应用程序。
server.stop()JupyUviAsync
JupyUviAsync (app, log_level='error', host='0.0.0.0', port=8000, **kwargs)
启动和停止一个与Jupyter兼容的异步uvicorn服务器,使用ASGI app在port上,日志级别为log_level
server = JupyUviAsync(app, port=port)
await server.start()async with AsyncClient() as client:
r = await client.get(f'http://localhost:{port}')
print(r.text)hi
server.stop()将笔记本用作网络应用
您还可以直接在笔记本中运行HTMX web应用。要使其工作,您必须使用show(*def_hdrs())将默认的FastHTML头部添加到笔记本的DOM中。此外,您可能会发现使用auto_id模式很方便,在这种模式下,如果未提供ID,则FT对象的ID会自动生成。
fh_cfg['auto_id' ]=True在导入 fasthtml.jupyter 并调用 render_ft() 之后,FT 组件会直接在笔记本中渲染。
show(*def_hdrs())
render_ft()(c := Div('Cogito ergo sum'))
我思故我在
处理程序的写法与常规网页应用相同:
server = JupyUvi(app, port=port)@rt
def hoho(): return P('loaded!'), Div('hee hee', id=c, hx_swap_oob='true')所有常用的 hx_* 属性都可以使用:
P('not loaded', hx_get=hoho, hx_trigger='load')未加载
FT 组件可以直接用作 id 值和 hx_target 值。
(c := Div(''))@rt
def foo(): return Div('foo bar')
P('hi', hx_get=foo, hx_trigger='load', hx_target=c)你好
server.stop()在 IFrame 中运行应用程序
使用IFrame可以很好地实现应用中样式和脚本的完全隔离。HTMX函数为网络应用创建一个自动调整大小的IFrame。
HTMX
HTMX (path='', app=None, host='localhost', port=8000, height='auto', link=False, iframe=True)
一个在笔记本中显示HTMX应用的iframe。
@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!'))server.start()# Run the notebook locally to see the HTMX iframe in action
HTMX()server.stop()ws_client
ws_client (app, nm='', host='localhost', port=8000, ws_connect='/ws', frame=True, link=True, **kwargs)