From ed03aeeb73699cfe7049acd5c39b9cb37c5736a9 Mon Sep 17 00:00:00 2001 From: Renato Gomes Damas Date: Tue, 20 Oct 2026 15:57:07 -0300 Subject: [PATCH 01/14] feat: introduce Alias class for handling request parameter aliases. close #937 --- fasthtml/_modidx.py | 1 + fasthtml/core.py | 41 +++++++++++++++++++------------ nbs/api/00_core.ipynb | 57 ++++++++++++++++++++++++++----------------- 3 files changed, 61 insertions(+), 38 deletions(-) diff --git a/fasthtml/_modidx.py b/fasthtml/_modidx.py index 8eb779a0..2a623f94 100644 --- a/fasthtml/_modidx.py +++ b/fasthtml/_modidx.py @@ -29,6 +29,7 @@ 'fasthtml.core.APIRouter._wrap_func': ('api/core.html#apirouter._wrap_func', 'fasthtml/core.py'), 'fasthtml.core.APIRouter.to_app': ('api/core.html#apirouter.to_app', 'fasthtml/core.py'), 'fasthtml.core.APIRouter.ws': ('api/core.html#apirouter.ws', 'fasthtml/core.py'), + 'fasthtml.core.Alias': ('api/core.html#alias', 'fasthtml/core.py'), 'fasthtml.core.ApiReturn': ('api/core.html#apireturn', 'fasthtml/core.py'), 'fasthtml.core.ApiReturn.__bool__': ('api/core.html#apireturn.__bool__', 'fasthtml/core.py'), 'fasthtml.core.ApiReturn.__call__': ('api/core.html#apireturn.__call__', 'fasthtml/core.py'), diff --git a/fasthtml/core.py b/fasthtml/core.py index e1539238..2dfa418f 100644 --- a/fasthtml/core.py +++ b/fasthtml/core.py @@ -18,7 +18,7 @@ class Cards: ... # class route group: each verb-named method (get, patch, . Handlers return FT trees (from `fastcore.xml`), rendered as HTML automatically: a full page for regular requests, a bare fragment for HTMX requests. In a full page, top-level `Title`, `Meta`, `Link`, and `Style` items go in ``; the rest goes in ``. Strings are sent as HTML, dicts as JSON, and a Starlette `Response` is sent untouched. A return tuple may mix content with special items: any `HttpHeader` (e.g. from `cookie()` or `HtmxResponseHeaders()`) becomes a response header, any `BackgroundTask` runs after the response is sent, and the rest renders as content. `Redirect` picks the right redirect mechanism for HTMX vs regular requests, and `FtResponse` wraps FT content when you need the status code or headers. -Handler parameters are filled from the request: each is looked up in path, cookie, header (snake_case names match Hyphen-Case headers), query, then form data, and cast by calling its annotation on the value. `bool`, `int`, and `date` get smart string parsing; `UploadFile` passes through. Repeated params take the last value unless annotated `list[T]`, which collects them all. A param with no annotation and no special name is ignored, with a warning. A dataclass, TypedDict, namedtuple, or any annotated class collects the whole form body; a `__from_request__` classmethod customizes construction. A missing required param is a 400, a failed cast a 404. These special names need no annotation: +Handler parameters are filled from the request: each is looked up in path, cookie, header (snake_case names match Hyphen-Case headers), query, then form data (use `Annotated[T, Alias('name')]` to read a different request name), and cast by calling its annotation on the value. `bool`, `int`, and `date` get smart string parsing; `UploadFile` passes through. Repeated params take the last value unless annotated `list[T]`, which collects them all. A param with no annotation and no special name is ignored, with a warning. A dataclass, TypedDict, namedtuple, or any annotated class collects the whole form body; a `__from_request__` classmethod customizes construction. A missing required param is a 400, a failed cast a 404. These special names need no annotation: req, ws the Request / WebSocket connection sess session dict @@ -48,11 +48,11 @@ class Cards: ... # class route group: each verb-named method (get, patch, . __all__ = ['empty', 'htmx_hdrs', 'fh_cfg', 'htmx_resps', 'DEF_MAXPART', 'htmx_exts', 'htmxsrc', 'htmx4src', 'fhjsscr', 'surrsrc', 'scopesrc', 'viewport', 'charset', 'cors_allow', 'iframe_scr', 'all_meths', 'devtools_loc', 'parsed_date', 'snake2hyphens', 'HtmxHeaders', 'HttpHeader', 'HtmxResponseHeaders', 'form2dict', 'parse_form', 'ApiReturn', - 'JSONResponse', 'flat_xt', 'Beforeware', 'EventStream', 'signal_shutdown', 'uri', 'decode_uri', 'flat_tuple', - 'noop_body', 'respond', 'is_full_page', 'Redirect', 'get_key', 'qp', 'def_hdrs', 'Lifespan', 'FastHTML', - 'HostRoute', 'nested_name', 'serve', 'until_disconnect', 'cancel_on_disconnect', 'Client', 'RouteFuncs', - 'APIRouter', 'cookie', 'reg_re_param', 'StaticNoCache', 'StaticImmutable', 'vurl', 'add_sig_param', 'into', - 'MiddlewareBase', 'FtResponse', 'unqid'] + 'JSONResponse', 'Alias', 'flat_xt', 'Beforeware', 'EventStream', 'signal_shutdown', 'uri', 'decode_uri', + 'flat_tuple', 'noop_body', 'respond', 'is_full_page', 'Redirect', 'get_key', 'qp', 'def_hdrs', 'Lifespan', + 'FastHTML', 'HostRoute', 'nested_name', 'serve', 'until_disconnect', 'cancel_on_disconnect', 'Client', + 'RouteFuncs', 'APIRouter', 'cookie', 'reg_re_param', 'StaticNoCache', 'StaticImmutable', 'vurl', + 'add_sig_param', 'into', 'MiddlewareBase', 'FtResponse', 'unqid'] # %% ../nbs/api/00_core.ipynb #23503b9e import json,uuid,inspect,types,asyncio,inspect,random,contextlib,itsdangerous,hashlib,signal,subprocess @@ -64,7 +64,7 @@ class Cards: ... # class route group: each verb-named method (get, patch, . from fastcore.style import S from types import UnionType, SimpleNamespace as ns, GenericAlias -from typing import get_args, get_origin, Union, Mapping, List, Any, Callable +from typing import get_args, get_origin, Union, Mapping, List, Any, Callable, Annotated from datetime import datetime,date from dataclasses import dataclass from inspect import Parameter,get_annotations @@ -257,8 +257,19 @@ def _default(o): return list(o) if is_listy(o) else str(o) # %% ../nbs/api/00_core.ipynb #5fa96e3a +@dataclass(frozen=True) +class Alias: + "Read a handler param from request data under `name` instead of its Python name, e.g. `Annotated[str, Alias('user-id')]`" + name: str + async def _find_p(conn, data, hdrs, arg:str, p:Parameter): "In `data` find param named `arg` of type in `p` (`arg` is ignored for body types)" + alias = None + if get_origin(p.annotation) is Annotated: + anno, *meta = get_args(p.annotation) + p = p.replace(annotation=anno) + alias = next((m.name for m in meta if isinstance(m, Alias)), None) + key = alias or arg anno = p.annotation # Special annotation types if isinstance(anno, type) and not isinstance(anno, GenericAlias): @@ -289,17 +300,17 @@ async def _find_p(conn, data, hdrs, arg:str, p:Parameter): if arg.lower() in ('hdrs','ftrs','bodykw','htmlkw'): return getattr(conn, arg.lower()) return None # Not a special name or a special annotation - res = conn.path_params.get(arg, None) - if res in (empty,None): res = conn.cookies.get(arg, None) - if res in (empty,None): res = hdrs.get(snake2hyphens(arg), None) - if res in (empty,None): res = conn.query_params.getlist(arg) + res = conn.path_params.get(key, None) + if res in (empty,None): res = conn.cookies.get(key, None) + if res in (empty,None): res = hdrs.get(alias or snake2hyphens(arg), None) + if res in (empty,None): res = conn.query_params.getlist(key) if res==[]: res = None - if res in (empty,None): res = data.get(arg, None) - if res in (empty,None) and isinstance(vals := data.get('values'), dict): res = vals.get(arg) # htmx v4 nests form data under `values` + if res in (empty,None): res = data.get(key, None) + if res in (empty,None) and isinstance(vals := data.get('values'), dict): res = vals.get(key) # htmx v4 nests form data under `values` if res in (empty,None): if p.default is empty: - if isinstance(conn, Request): raise HTTPException(400, f"Missing required field: {arg}") - raise ValueError(f"Missing required field: {arg}") + if isinstance(conn, Request): raise HTTPException(400, f"Missing required field: {key}") + raise ValueError(f"Missing required field: {key}") res = p.default try: return _fix_anno(anno, res) except ValueError as e: diff --git a/nbs/api/00_core.ipynb b/nbs/api/00_core.ipynb index 1fa7a1c4..f16e791c 100644 --- a/nbs/api/00_core.ipynb +++ b/nbs/api/00_core.ipynb @@ -43,7 +43,7 @@ "\n", "Handlers return FT trees (from `fastcore.xml`), rendered as HTML automatically: a full page for regular requests, a bare fragment for HTMX requests. In a full page, top-level `Title`, `Meta`, `Link`, and `Style` items go in ``; the rest goes in ``. Strings are sent as HTML, dicts as JSON, and a Starlette `Response` is sent untouched. A return tuple may mix content with special items: any `HttpHeader` (e.g. from `cookie()` or `HtmxResponseHeaders()`) becomes a response header, any `BackgroundTask` runs after the response is sent, and the rest renders as content. `Redirect` picks the right redirect mechanism for HTMX vs regular requests, and `FtResponse` wraps FT content when you need the status code or headers.\n", "\n", - "Handler parameters are filled from the request: each is looked up in path, cookie, header (snake_case names match Hyphen-Case headers), query, then form data, and cast by calling its annotation on the value. `bool`, `int`, and `date` get smart string parsing; `UploadFile` passes through. Repeated params take the last value unless annotated `list[T]`, which collects them all. A param with no annotation and no special name is ignored, with a warning. A dataclass, TypedDict, namedtuple, or any annotated class collects the whole form body; a `__from_request__` classmethod customizes construction. A missing required param is a 400, a failed cast a 404. These special names need no annotation:\n", + "Handler parameters are filled from the request: each is looked up in path, cookie, header (snake_case names match Hyphen-Case headers), query, then form data (use `Annotated[T, Alias('name')]` to read a different request name), and cast by calling its annotation on the value. `bool`, `int`, and `date` get smart string parsing; `UploadFile` passes through. Repeated params take the last value unless annotated `list[T]`, which collects them all. A param with no annotation and no special name is ignored, with a warning. A dataclass, TypedDict, namedtuple, or any annotated class collects the whole form body; a `__from_request__` classmethod customizes construction. A missing required param is a 400, a failed cast a 404. These special names need no annotation:\n", "\n", " req, ws the Request / WebSocket connection\n", " sess session dict\n", @@ -99,7 +99,7 @@ "from fastcore.style import S\n", "\n", "from types import UnionType, SimpleNamespace as ns, GenericAlias\n", - "from typing import get_args, get_origin, Union, Mapping, List, Any, Callable\n", + "from typing import get_args, get_origin, Union, Mapping, List, Any, Callable, Annotated\n", "from datetime import datetime,date\n", "from dataclasses import dataclass\n", "from inspect import Parameter,get_annotations\n", @@ -895,8 +895,19 @@ "outputs": [], "source": [ "#| export\n", + "@dataclass(frozen=True)\n", + "class Alias:\n", + " \"Read a handler param from request data under `name` instead of its Python name, e.g. `Annotated[str, Alias('user-id')]`\"\n", + " name: str\n", + "\n", "async def _find_p(conn, data, hdrs, arg:str, p:Parameter):\n", " \"In `data` find param named `arg` of type in `p` (`arg` is ignored for body types)\"\n", + " alias = None\n", + " if get_origin(p.annotation) is Annotated:\n", + " anno, *meta = get_args(p.annotation)\n", + " p = p.replace(annotation=anno)\n", + " alias = next((m.name for m in meta if isinstance(m, Alias)), None)\n", + " key = alias or arg\n", " anno = p.annotation\n", " # Special annotation types\n", " if isinstance(anno, type) and not isinstance(anno, GenericAlias):\n", @@ -927,17 +938,17 @@ " if arg.lower() in ('hdrs','ftrs','bodykw','htmlkw'): return getattr(conn, arg.lower())\n", " return None\n", " # Not a special name or a special annotation\n", - " res = conn.path_params.get(arg, None)\n", - " if res in (empty,None): res = conn.cookies.get(arg, None)\n", - " if res in (empty,None): res = hdrs.get(snake2hyphens(arg), None)\n", - " if res in (empty,None): res = conn.query_params.getlist(arg)\n", + " res = conn.path_params.get(key, None)\n", + " if res in (empty,None): res = conn.cookies.get(key, None)\n", + " if res in (empty,None): res = hdrs.get(alias or snake2hyphens(arg), None)\n", + " if res in (empty,None): res = conn.query_params.getlist(key)\n", " if res==[]: res = None\n", - " if res in (empty,None): res = data.get(arg, None)\n", - " if res in (empty,None) and isinstance(vals := data.get('values'), dict): res = vals.get(arg) # htmx v4 nests form data under `values`\n", + " if res in (empty,None): res = data.get(key, None)\n", + " if res in (empty,None) and isinstance(vals := data.get('values'), dict): res = vals.get(key) # htmx v4 nests form data under `values`\n", " if res in (empty,None):\n", " if p.default is empty:\n", - " if isinstance(conn, Request): raise HTTPException(400, f\"Missing required field: {arg}\")\n", - " raise ValueError(f\"Missing required field: {arg}\")\n", + " if isinstance(conn, Request): raise HTTPException(400, f\"Missing required field: {key}\")\n", + " raise ValueError(f\"Missing required field: {key}\")\n", " res = p.default\n", " try: return _fix_anno(anno, res)\n", " except ValueError as e:\n", @@ -945,19 +956,6 @@ " raise" ] }, - { - "cell_type": "code", - "execution_count": null, - "id": "bf42edad", - "metadata": {}, - "outputs": [], - "source": [ - "#| export\n", - "async def _find_ps(conn, data, hdrs, params):\n", - " if conn.query_params: data |= dict(conn.query_params)\n", - " return {arg:await _find_p(conn, data, hdrs, arg, p) for arg,p in params.items()}" - ] - }, { "cell_type": "code", "execution_count": null, @@ -980,6 +978,19 @@ "await _from_body(req, p, data)" ] }, + { + "cell_type": "code", + "execution_count": null, + "id": "bf42edad", + "metadata": {}, + "outputs": [], + "source": [ + "#| export\n", + "async def _find_ps(conn, data, hdrs, params):\n", + " if conn.query_params: data |= dict(conn.query_params)\n", + " return {arg:await _find_p(conn, data, hdrs, arg, p) for arg,p in params.items()}" + ] + }, { "cell_type": "code", "execution_count": null, From 19430ad836c252b196831c639d725151ca0ca000 Mon Sep 17 00:00:00 2001 From: Renato Gomes Damas Date: Tue, 20 Oct 2026 16:18:20 -0300 Subject: [PATCH 02/14] test: add tests for request parameter alias handling --- tests/test_alias.py | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 tests/test_alias.py diff --git a/tests/test_alias.py b/tests/test_alias.py new file mode 100644 index 00000000..059fe82b --- /dev/null +++ b/tests/test_alias.py @@ -0,0 +1,42 @@ +from fasthtml.common import * +from starlette.testclient import TestClient +from typing import Annotated + +app, rt = fast_app() +cli = TestClient(app) + +@rt("/query") +def get(user_id: Annotated[str, Alias("user-id")]): return f"q:{user_id}" + +@rt("/form", methods=["post"]) +def post(user_id: Annotated[str, Alias("user-id")]): return f"f:{user_id}" + +@rt("/path/{item_id}") +def get(item_id: Annotated[int, Alias("item_id")]): return f"p:{item_id}" + +@rt("/header") +def get(x_api_key: Annotated[str, Alias("X-Api-Key")]): return f"h:{x_api_key}" + +@rt("/cookie") +def get(req, session_id: Annotated[str, Alias("session-id")]): return f"c:{session_id}" + +@rt("/int") +def get(count: Annotated[int, Alias("the-count")]): return f"i:{count + 1}" + +@rt("/plain") +def get(user_id: str): return f"plain:{user_id}" + +@rt("/missing") +def get(user_id: Annotated[str, Alias("user-id")]): return user_id + +def test_query_alias(): assert cli.get('/query?user-id=abc').text == 'q:abc' +def test_form_alias(): assert cli.post('/form', data={'user-id': 'abc'}).text == 'f:abc' +def test_path_alias(): assert cli.get('/path/7').text == 'p:7' +def test_header_alias(): assert cli.get('/header', headers={'X-Api-Key': 'k1'}).text == 'h:k1' +def test_cookie_alias(): assert cli.get('/cookie', cookies={'session-id': 's1'}).text == 'c:s1' +def test_int_alias(): assert cli.get('/int?the-count=4').text == 'i:5' +def test_plain_unchanged(): assert cli.get('/plain?user_id=z').text == 'plain:z' +def test_snake_name_not_used_for_alias(): assert cli.get('/query?user_id=abc').status_code == 400 +def test_missing_message_uses_alias(): + r = cli.get('/missing') + assert r.status_code == 400 and 'Missing required field: user-id' in r.text From 4e239aeabea765f95dfb3cbdb1349840212635a1 Mon Sep 17 00:00:00 2001 From: Renato Gomes Damas Date: Tue, 20 Oct 2026 16:43:08 -0300 Subject: [PATCH 03/14] refactor: update code cell metadata in 00_core.ipynb --- nbs/api/00_core.ipynb | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/nbs/api/00_core.ipynb b/nbs/api/00_core.ipynb index f16e791c..dee11489 100644 --- a/nbs/api/00_core.ipynb +++ b/nbs/api/00_core.ipynb @@ -1,14 +1,12 @@ { "cells": [ { - "cell_type": "code", - "execution_count": null, - "id": "fa505c58", "metadata": {}, + "cell_type": "code", "outputs": [], - "source": [ - "#| default_exp core" - ] + "execution_count": null, + "source": "#| default_exp core", + "id": "2ae074a97d562882" }, { "cell_type": "markdown", From 2828e31f23259e6f85f64336cfd5f5cc98d98eea Mon Sep 17 00:00:00 2001 From: Renato Gomes Damas Date: Tue, 20 Oct 2026 17:06:04 -0300 Subject: [PATCH 04/14] refactor: update code cell structure --- nbs/api/00_core.ipynb | 36 +++++++++++++++++++----------------- 1 file changed, 19 insertions(+), 17 deletions(-) diff --git a/nbs/api/00_core.ipynb b/nbs/api/00_core.ipynb index dee11489..ebc2c45c 100644 --- a/nbs/api/00_core.ipynb +++ b/nbs/api/00_core.ipynb @@ -1,12 +1,14 @@ { "cells": [ { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, - "source": "#| default_exp core", - "id": "2ae074a97d562882" + "id": "fa505c58", + "metadata": {}, + "outputs": [], + "source": [ + "#| default_exp core" + ] }, { "cell_type": "markdown", @@ -954,6 +956,19 @@ " raise" ] }, + { + "cell_type": "code", + "execution_count": null, + "id": "bf42edad", + "metadata": {}, + "outputs": [], + "source": [ + "#| export\n", + "async def _find_ps(conn, data, hdrs, params):\n", + " if conn.query_params: data |= dict(conn.query_params)\n", + " return {arg:await _find_p(conn, data, hdrs, arg, p) for arg,p in params.items()}" + ] + }, { "cell_type": "code", "execution_count": null, @@ -976,19 +991,6 @@ "await _from_body(req, p, data)" ] }, - { - "cell_type": "code", - "execution_count": null, - "id": "bf42edad", - "metadata": {}, - "outputs": [], - "source": [ - "#| export\n", - "async def _find_ps(conn, data, hdrs, params):\n", - " if conn.query_params: data |= dict(conn.query_params)\n", - " return {arg:await _find_p(conn, data, hdrs, arg, p) for arg,p in params.items()}" - ] - }, { "cell_type": "code", "execution_count": null, From dfc4ea3476b85753c40bf6acd6883db9fd568b5a Mon Sep 17 00:00:00 2001 From: Jeremy Howard Date: Wed, 21 Oct 2026 08:56:16 +1000 Subject: [PATCH 05/14] fixes #939 --- fasthtml/core.py | 13 +++++++------ nbs/api/00_core.ipynb | 33 ++++++++++++++++++--------------- 2 files changed, 25 insertions(+), 21 deletions(-) diff --git a/fasthtml/core.py b/fasthtml/core.py index e1539238..58c00f4c 100644 --- a/fasthtml/core.py +++ b/fasthtml/core.py @@ -18,7 +18,7 @@ class Cards: ... # class route group: each verb-named method (get, patch, . Handlers return FT trees (from `fastcore.xml`), rendered as HTML automatically: a full page for regular requests, a bare fragment for HTMX requests. In a full page, top-level `Title`, `Meta`, `Link`, and `Style` items go in ``; the rest goes in ``. Strings are sent as HTML, dicts as JSON, and a Starlette `Response` is sent untouched. A return tuple may mix content with special items: any `HttpHeader` (e.g. from `cookie()` or `HtmxResponseHeaders()`) becomes a response header, any `BackgroundTask` runs after the response is sent, and the rest renders as content. `Redirect` picks the right redirect mechanism for HTMX vs regular requests, and `FtResponse` wraps FT content when you need the status code or headers. -Handler parameters are filled from the request: each is looked up in path, cookie, header (snake_case names match Hyphen-Case headers), query, then form data, and cast by calling its annotation on the value. `bool`, `int`, and `date` get smart string parsing; `UploadFile` passes through. Repeated params take the last value unless annotated `list[T]`, which collects them all. A param with no annotation and no special name is ignored, with a warning. A dataclass, TypedDict, namedtuple, or any annotated class collects the whole form body; a `__from_request__` classmethod customizes construction. A missing required param is a 400, a failed cast a 404. These special names need no annotation: +Handler parameters are filled from the request: each is looked up in path, cookie, header (snake_case names match Hyphen-Case headers), query, then form data, and cast by calling its annotation on the value. Hyphens in form/query names match underscores in handler parameters and typed body fields. Exact names take precedence within each source. Dictionary and request access retain the original keys. `bool`, `int`, and `date` get smart string parsing; `UploadFile` passes through. Repeated params take the last value unless annotated `list[T]`, which collects them all. A param with no annotation and no special name is ignored, with a warning. A dataclass, TypedDict, namedtuple, or any annotated class collects the whole form body; a `__from_request__` classmethod customizes construction. A missing required param is a 400, a failed cast a 404. These special names need no annotation: req, ws the Request / WebSocket connection sess session dict @@ -190,7 +190,8 @@ def _is_body(anno): return issubclass(anno, (dict,ns)) or hasattr(anno,'__from_r # %% ../nbs/api/00_core.ipynb #ffdde66f def _formitem(form, k): - "Return single item `k` from `form` if len 1, otherwise return list" + "Return item `k`, accepting hyphens for underscores and unwrapping single-item form lists" + if k not in form: k = {o.replace('-', '_'):o for o in form}.get(k, k) if isinstance(form, dict): return form.get(k) o = form.getlist(k) return o[0] if len(o) == 1 else o if o else None @@ -235,6 +236,7 @@ async def _from_body(conn, p, data): kwargs = await _find_ps(conn, data, conn.headers, ps) return await maybe_await(ctor(**kwargs)) d = _annotations(anno) + if d: data = {k.replace('-', '_'):v for k,v in data.items()} | data cargs = {k: _form_arg(k, v, d) for k, v in data.items() if not d or k in d} return anno(**cargs) @@ -292,10 +294,9 @@ async def _find_p(conn, data, hdrs, arg:str, p:Parameter): res = conn.path_params.get(arg, None) if res in (empty,None): res = conn.cookies.get(arg, None) if res in (empty,None): res = hdrs.get(snake2hyphens(arg), None) - if res in (empty,None): res = conn.query_params.getlist(arg) - if res==[]: res = None - if res in (empty,None): res = data.get(arg, None) - if res in (empty,None) and isinstance(vals := data.get('values'), dict): res = vals.get(arg) # htmx v4 nests form data under `values` + if res in (empty,None): res = _formitem(conn.query_params, arg) + if res in (empty,None): res = _formitem(data, arg) + if res in (empty,None) and isinstance(vals := data.get('values'), dict): res = _formitem(vals, arg) # htmx v4 nests form data under `values` if res in (empty,None): if p.default is empty: if isinstance(conn, Request): raise HTTPException(400, f"Missing required field: {arg}") diff --git a/nbs/api/00_core.ipynb b/nbs/api/00_core.ipynb index 1fa7a1c4..9238c3a0 100644 --- a/nbs/api/00_core.ipynb +++ b/nbs/api/00_core.ipynb @@ -43,7 +43,7 @@ "\n", "Handlers return FT trees (from `fastcore.xml`), rendered as HTML automatically: a full page for regular requests, a bare fragment for HTMX requests. In a full page, top-level `Title`, `Meta`, `Link`, and `Style` items go in ``; the rest goes in ``. Strings are sent as HTML, dicts as JSON, and a Starlette `Response` is sent untouched. A return tuple may mix content with special items: any `HttpHeader` (e.g. from `cookie()` or `HtmxResponseHeaders()`) becomes a response header, any `BackgroundTask` runs after the response is sent, and the rest renders as content. `Redirect` picks the right redirect mechanism for HTMX vs regular requests, and `FtResponse` wraps FT content when you need the status code or headers.\n", "\n", - "Handler parameters are filled from the request: each is looked up in path, cookie, header (snake_case names match Hyphen-Case headers), query, then form data, and cast by calling its annotation on the value. `bool`, `int`, and `date` get smart string parsing; `UploadFile` passes through. Repeated params take the last value unless annotated `list[T]`, which collects them all. A param with no annotation and no special name is ignored, with a warning. A dataclass, TypedDict, namedtuple, or any annotated class collects the whole form body; a `__from_request__` classmethod customizes construction. A missing required param is a 400, a failed cast a 404. These special names need no annotation:\n", + "Handler parameters are filled from the request: each is looked up in path, cookie, header (snake_case names match Hyphen-Case headers), query, then form data, and cast by calling its annotation on the value. Hyphens in form/query names match underscores in handler parameters and typed body fields. Exact names take precedence within each source. Dictionary and request access retain the original keys. `bool`, `int`, and `date` get smart string parsing; `UploadFile` passes through. Repeated params take the last value unless annotated `list[T]`, which collects them all. A param with no annotation and no special name is ignored, with a warning. A dataclass, TypedDict, namedtuple, or any annotated class collects the whole form body; a `__from_request__` classmethod customizes construction. A missing required param is a 400, a failed cast a 404. These special names need no annotation:\n", "\n", " req, ws the Request / WebSocket connection\n", " sess session dict\n", @@ -603,7 +603,8 @@ "source": [ "#| export\n", "def _formitem(form, k):\n", - " \"Return single item `k` from `form` if len 1, otherwise return list\"\n", + " \"Return item `k`, accepting hyphens for underscores and unwrapping single-item form lists\"\n", + " if k not in form: k = {o.replace('-', '_'):o for o in form}.get(k, k)\n", " if isinstance(form, dict): return form.get(k)\n", " o = form.getlist(k)\n", " return o[0] if len(o) == 1 else o if o else None" @@ -730,6 +731,7 @@ " kwargs = await _find_ps(conn, data, conn.headers, ps)\n", " return await maybe_await(ctor(**kwargs))\n", " d = _annotations(anno)\n", + " if d: data = {k.replace('-', '_'):v for k,v in data.items()} | data\n", " cargs = {k: _form_arg(k, v, d) for k, v in data.items() if not d or k in d}\n", " return anno(**cargs)" ] @@ -930,10 +932,9 @@ " res = conn.path_params.get(arg, None)\n", " if res in (empty,None): res = conn.cookies.get(arg, None)\n", " if res in (empty,None): res = hdrs.get(snake2hyphens(arg), None)\n", - " if res in (empty,None): res = conn.query_params.getlist(arg)\n", - " if res==[]: res = None\n", - " if res in (empty,None): res = data.get(arg, None)\n", - " if res in (empty,None) and isinstance(vals := data.get('values'), dict): res = vals.get(arg) # htmx v4 nests form data under `values`\n", + " if res in (empty,None): res = _formitem(conn.query_params, arg)\n", + " if res in (empty,None): res = _formitem(data, arg)\n", + " if res in (empty,None) and isinstance(vals := data.get('values'), dict): res = _formitem(vals, arg) # htmx v4 nests form data under `values`\n", " if res in (empty,None):\n", " if p.default is empty:\n", " if isinstance(conn, Request): raise HTTPException(400, f\"Missing required field: {arg}\")\n", @@ -3408,10 +3409,12 @@ "outputs": [], "source": [ "@app.post('/profile/me')\n", - "def profile_update(username: str): return username\n", + "def profile_update(user_name: str): return user_name\n", "\n", - "test_r(cli, '/profile/me', 'Alexis', 'post', data={'username' : 'Alexis'})\n", - "test_r(cli, '/profile/me', 'Missing required field: username', 'post', data={})" + "test_r(cli, '/profile/me', 'Alexis', 'post', data={'user-name':'Alexis'})\n", + "test_r(cli, '/profile/me?user-name=Jeremy&user-name=Alexis', 'Alexis', 'post')\n", + "test_r(cli, '/profile/me', 'Jeremy', 'post', data={'user-name':'Alexis', 'user_name':'Jeremy'})\n", + "test_r(cli, '/profile/me', 'Missing required field: user_name', 'post', data={})" ] }, { @@ -3462,11 +3465,11 @@ "def bodient(data:BodieTD): return data\n", "\n", "class Bodie2:\n", - " a:int|None; b:str\n", - " def __init__(self, a, b='foo'): store_attr()\n", + " a_val:int|None; b:str\n", + " def __init__(self, a_val, b='foo'): store_attr()\n", "\n", "@rt(\"/bodie2/\", methods=['get','post'])\n", - "def bodie(d:Bodie2): return f\"a: {d.a}; b: {d.b}\"" + "def bodie(d:Bodie2): return f\"a: {d.a_val}; b: {d.b}\"" ] }, { @@ -3490,9 +3493,9 @@ "\n", "test_r(cli, '/bodie/me', '{\"a\":1,\"b\":\"foo\",\"nm\":\"me\"}', 'post', data=dict(a=1, b='foo', nm='me'))\n", "test_r(cli, '/cards/abc', '{\"id\":\"abc\",\"title\":\"Foo\"}', 'put', data={'title':'Foo'})\n", - "test_r(cli, '/bodied/', '{\"a\":\"1\",\"b\":\"foo\"}', 'post', data=d)\n", - "test_r(cli, '/bodie2/', 'a: 1; b: foo', 'post', data={'a':1})\n", - "test_r(cli, '/bodie2/?a=1&b=foo&nm=me', 'a: 1; b: foo')\n", + "test_r(cli, '/bodied/', '{\"user-name\":\"Alexis\"}', 'post', data={'user-name':'Alexis'})\n", + "test_r(cli, '/bodie2/', 'a: 1; b: foo', 'post', data={'a-val':2, 'a_val':1})\n", + "test_r(cli, '/bodie2/?a-val=1&b=foo&nm=me', 'a: 1; b: foo')\n", "test_r(cli, '/bodient/', '{\"a\":\"1\",\"b\":\"foo\"}', 'post', data=d)\n", "test_r(cli, '/bodietd/', '{\"a\":1,\"b\":\"foo\"}', 'post', data=d)" ] From 54f58597ed6c2cfce5b44a2ae448bc8b21a55b9f Mon Sep 17 00:00:00 2001 From: Jeremy Howard Date: Wed, 21 Oct 2026 09:01:46 +1000 Subject: [PATCH 06/14] format --- nbs/nbdev.yml | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/nbs/nbdev.yml b/nbs/nbdev.yml index e5895a03..7216b139 100644 --- a/nbs/nbdev.yml +++ b/nbs/nbdev.yml @@ -7,3 +7,8 @@ website: description: "The fastest way to create an HTML app" repo-branch: main repo-url: "https://github.com/AnswerDotAI/fasthtml" + +format-links: + - html + - format: commonmark + text: Markdown From 2eb7db8796fa8eca0b746233dbdc3f7db02d5c94 Mon Sep 17 00:00:00 2001 From: Jeremy Howard Date: Wed, 21 Oct 2026 09:02:09 +1000 Subject: [PATCH 07/14] release --- CHANGELOG.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index b182811a..1fc2e16e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,14 @@ +## 0.14.14 + +### New Features + +- Match hyphenated form/query names to underscore handler params and body fields, with exact names taking precedence ([#939](https://github.com/AnswerDotAI/fasthtml/issues/939)) +- Return 400 for malformed multipart and invalid JSON bodies; redirect to error path with `oauth_error` on OAuth token exchange failure ([#929](https://github.com/AnswerDotAI/fasthtml/issues/929)) + + ## 0.14.13 ### New Features From 447dee49630ea2fe449a36c84764b75c5cff2c4f Mon Sep 17 00:00:00 2001 From: Jeremy Howard Date: Wed, 21 Oct 2026 09:02:22 +1000 Subject: [PATCH 08/14] bump [skip ci] --- fasthtml/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/fasthtml/__init__.py b/fasthtml/__init__.py index da9002e4..cb62b6db 100644 --- a/fasthtml/__init__.py +++ b/fasthtml/__init__.py @@ -4,5 +4,5 @@ - `fasthtml.core`: The `FastHTML` subclass of `Starlette`.""" -__version__ = "0.14.14" +__version__ = "0.14.15" from .core import * From 71b3e941f8e96aa0d713fed61e80d0a5146ba92f Mon Sep 17 00:00:00 2001 From: Renato Gomes Damas Date: Tue, 20 Oct 2026 15:57:07 -0300 Subject: [PATCH 09/14] feat: introduce Alias class for handling request parameter aliases. close #937 --- fasthtml/_modidx.py | 1 + fasthtml/core.py | 43 +- nbs/api/00_core.ipynb | 3066 +++++++++++++++-------------------------- 3 files changed, 1164 insertions(+), 1946 deletions(-) diff --git a/fasthtml/_modidx.py b/fasthtml/_modidx.py index 8eb779a0..2a623f94 100644 --- a/fasthtml/_modidx.py +++ b/fasthtml/_modidx.py @@ -29,6 +29,7 @@ 'fasthtml.core.APIRouter._wrap_func': ('api/core.html#apirouter._wrap_func', 'fasthtml/core.py'), 'fasthtml.core.APIRouter.to_app': ('api/core.html#apirouter.to_app', 'fasthtml/core.py'), 'fasthtml.core.APIRouter.ws': ('api/core.html#apirouter.ws', 'fasthtml/core.py'), + 'fasthtml.core.Alias': ('api/core.html#alias', 'fasthtml/core.py'), 'fasthtml.core.ApiReturn': ('api/core.html#apireturn', 'fasthtml/core.py'), 'fasthtml.core.ApiReturn.__bool__': ('api/core.html#apireturn.__bool__', 'fasthtml/core.py'), 'fasthtml.core.ApiReturn.__call__': ('api/core.html#apireturn.__call__', 'fasthtml/core.py'), diff --git a/fasthtml/core.py b/fasthtml/core.py index 58c00f4c..894096cb 100644 --- a/fasthtml/core.py +++ b/fasthtml/core.py @@ -18,7 +18,7 @@ class Cards: ... # class route group: each verb-named method (get, patch, . Handlers return FT trees (from `fastcore.xml`), rendered as HTML automatically: a full page for regular requests, a bare fragment for HTMX requests. In a full page, top-level `Title`, `Meta`, `Link`, and `Style` items go in ``; the rest goes in ``. Strings are sent as HTML, dicts as JSON, and a Starlette `Response` is sent untouched. A return tuple may mix content with special items: any `HttpHeader` (e.g. from `cookie()` or `HtmxResponseHeaders()`) becomes a response header, any `BackgroundTask` runs after the response is sent, and the rest renders as content. `Redirect` picks the right redirect mechanism for HTMX vs regular requests, and `FtResponse` wraps FT content when you need the status code or headers. -Handler parameters are filled from the request: each is looked up in path, cookie, header (snake_case names match Hyphen-Case headers), query, then form data, and cast by calling its annotation on the value. Hyphens in form/query names match underscores in handler parameters and typed body fields. Exact names take precedence within each source. Dictionary and request access retain the original keys. `bool`, `int`, and `date` get smart string parsing; `UploadFile` passes through. Repeated params take the last value unless annotated `list[T]`, which collects them all. A param with no annotation and no special name is ignored, with a warning. A dataclass, TypedDict, namedtuple, or any annotated class collects the whole form body; a `__from_request__` classmethod customizes construction. A missing required param is a 400, a failed cast a 404. These special names need no annotation: +Handler parameters are filled from the request: each is looked up in path, cookie, header (snake_case names match Hyphen-Case headers), query, then form data (use `Annotated[T, Alias('name')]` to read a different request name), and cast by calling its annotation on the value. Hyphens in form/query names match underscores in handler parameters and typed body fields. Exact names take precedence within each source. Dictionary and request access retain the original keys. `bool`, `int`, and `date` get smart string parsing; `UploadFile` passes through. Repeated params take the last value unless annotated `list[T]`, which collects them all. A param with no annotation and no special name is ignored, with a warning. A dataclass, TypedDict, namedtuple, or any annotated class collects the whole form body; a `__from_request__` classmethod customizes construction. A missing required param is a 400, a failed cast a 404. These special names need no annotation: req, ws the Request / WebSocket connection sess session dict @@ -48,11 +48,11 @@ class Cards: ... # class route group: each verb-named method (get, patch, . __all__ = ['empty', 'htmx_hdrs', 'fh_cfg', 'htmx_resps', 'DEF_MAXPART', 'htmx_exts', 'htmxsrc', 'htmx4src', 'fhjsscr', 'surrsrc', 'scopesrc', 'viewport', 'charset', 'cors_allow', 'iframe_scr', 'all_meths', 'devtools_loc', 'parsed_date', 'snake2hyphens', 'HtmxHeaders', 'HttpHeader', 'HtmxResponseHeaders', 'form2dict', 'parse_form', 'ApiReturn', - 'JSONResponse', 'flat_xt', 'Beforeware', 'EventStream', 'signal_shutdown', 'uri', 'decode_uri', 'flat_tuple', - 'noop_body', 'respond', 'is_full_page', 'Redirect', 'get_key', 'qp', 'def_hdrs', 'Lifespan', 'FastHTML', - 'HostRoute', 'nested_name', 'serve', 'until_disconnect', 'cancel_on_disconnect', 'Client', 'RouteFuncs', - 'APIRouter', 'cookie', 'reg_re_param', 'StaticNoCache', 'StaticImmutable', 'vurl', 'add_sig_param', 'into', - 'MiddlewareBase', 'FtResponse', 'unqid'] + 'JSONResponse', 'Alias', 'flat_xt', 'Beforeware', 'EventStream', 'signal_shutdown', 'uri', 'decode_uri', + 'flat_tuple', 'noop_body', 'respond', 'is_full_page', 'Redirect', 'get_key', 'qp', 'def_hdrs', 'Lifespan', + 'FastHTML', 'HostRoute', 'nested_name', 'serve', 'until_disconnect', 'cancel_on_disconnect', 'Client', + 'RouteFuncs', 'APIRouter', 'cookie', 'reg_re_param', 'StaticNoCache', 'StaticImmutable', 'vurl', + 'add_sig_param', 'into', 'MiddlewareBase', 'FtResponse', 'unqid'] # %% ../nbs/api/00_core.ipynb #23503b9e import json,uuid,inspect,types,asyncio,inspect,random,contextlib,itsdangerous,hashlib,signal,subprocess @@ -64,7 +64,7 @@ class Cards: ... # class route group: each verb-named method (get, patch, . from fastcore.style import S from types import UnionType, SimpleNamespace as ns, GenericAlias -from typing import get_args, get_origin, Union, Mapping, List, Any, Callable +from typing import get_args, get_origin, Union, Mapping, List, Any, Callable, Annotated from datetime import datetime,date from dataclasses import dataclass from inspect import Parameter,get_annotations @@ -259,8 +259,19 @@ def _default(o): return list(o) if is_listy(o) else str(o) # %% ../nbs/api/00_core.ipynb #5fa96e3a +@dataclass(frozen=True) +class Alias: + "Read a handler param from request data under `name` instead of its Python name, e.g. `Annotated[str, Alias('user-id')]`" + name: str + async def _find_p(conn, data, hdrs, arg:str, p:Parameter): "In `data` find param named `arg` of type in `p` (`arg` is ignored for body types)" + alias = None + if get_origin(p.annotation) is Annotated: + anno, *meta = get_args(p.annotation) + p = p.replace(annotation=anno) + alias = next((m.name for m in meta if isinstance(m, Alias)), None) + key = alias or arg anno = p.annotation # Special annotation types if isinstance(anno, type) and not isinstance(anno, GenericAlias): @@ -270,7 +281,7 @@ async def _find_p(conn, data, hdrs, arg:str, p:Parameter): if issubclass(anno, State): return conn.scope['app'].state if anno is dict: return data if _is_body(anno): - if 'session'.startswith(arg.lower()): return conn.scope.get('session', {}) + if 'session'.startswith(key.lower()): return conn.scope.get('session', {}) return await _from_body(conn, p, data) if (msg := _check_anno(arg, anno)): return warn(msg) # Special param names with no annotations @@ -291,16 +302,16 @@ async def _find_p(conn, data, hdrs, arg:str, p:Parameter): if arg.lower() in ('hdrs','ftrs','bodykw','htmlkw'): return getattr(conn, arg.lower()) return None # Not a special name or a special annotation - res = conn.path_params.get(arg, None) - if res in (empty,None): res = conn.cookies.get(arg, None) - if res in (empty,None): res = hdrs.get(snake2hyphens(arg), None) - if res in (empty,None): res = _formitem(conn.query_params, arg) - if res in (empty,None): res = _formitem(data, arg) - if res in (empty,None) and isinstance(vals := data.get('values'), dict): res = _formitem(vals, arg) # htmx v4 nests form data under `values` + res = conn.path_params.get(key, None) + if res in (empty,None): res = conn.cookies.get(key, None) + if res in (empty,None): res = hdrs.get(alias or snake2hyphens(key), None) + if res in (empty,None): res = _formitem(conn.query_params, key) + if res in (empty,None): res = _formitem(data, key) + if res in (empty,None) and isinstance(vals := data.get('values'), dict): res = _formitem(vals, key) # htmx v4 nests form data under `values` if res in (empty,None): if p.default is empty: - if isinstance(conn, Request): raise HTTPException(400, f"Missing required field: {arg}") - raise ValueError(f"Missing required field: {arg}") + if isinstance(conn, Request): raise HTTPException(400, f"Missing required field: {key}") + raise ValueError(f"Missing required field: {key}") res = p.default try: return _fix_anno(anno, res) except ValueError as e: diff --git a/nbs/api/00_core.ipynb b/nbs/api/00_core.ipynb index 9238c3a0..95a8cf01 100644 --- a/nbs/api/00_core.ipynb +++ b/nbs/api/00_core.ipynb @@ -1,28 +1,25 @@ { "cells": [ { - "cell_type": "code", - "execution_count": null, - "id": "fa505c58", "metadata": {}, + "cell_type": "code", "outputs": [], - "source": [ - "#| default_exp core" - ] + "execution_count": null, + "source": "#| default_exp core", + "id": "7f686573b69acc40" }, { - "cell_type": "markdown", - "id": "2161d9b5", "metadata": {}, + "cell_type": "markdown", "source": [ "# Core\n", "> The `FastHTML` subclass of `Starlette`." - ] + ], + "id": "59798c88b0200b3c" }, { - "cell_type": "markdown", - "id": "1f8f308f", "metadata": {}, + "cell_type": "markdown", "source": [ "#| export\n", "Create an app with `app = FastHTML()`. The `@rt` decorator adds routes (`rt = app.route`), inferring what it can from the function:\n", @@ -43,7 +40,7 @@ "\n", "Handlers return FT trees (from `fastcore.xml`), rendered as HTML automatically: a full page for regular requests, a bare fragment for HTMX requests. In a full page, top-level `Title`, `Meta`, `Link`, and `Style` items go in ``; the rest goes in ``. Strings are sent as HTML, dicts as JSON, and a Starlette `Response` is sent untouched. A return tuple may mix content with special items: any `HttpHeader` (e.g. from `cookie()` or `HtmxResponseHeaders()`) becomes a response header, any `BackgroundTask` runs after the response is sent, and the rest renders as content. `Redirect` picks the right redirect mechanism for HTMX vs regular requests, and `FtResponse` wraps FT content when you need the status code or headers.\n", "\n", - "Handler parameters are filled from the request: each is looked up in path, cookie, header (snake_case names match Hyphen-Case headers), query, then form data, and cast by calling its annotation on the value. Hyphens in form/query names match underscores in handler parameters and typed body fields. Exact names take precedence within each source. Dictionary and request access retain the original keys. `bool`, `int`, and `date` get smart string parsing; `UploadFile` passes through. Repeated params take the last value unless annotated `list[T]`, which collects them all. A param with no annotation and no special name is ignored, with a warning. A dataclass, TypedDict, namedtuple, or any annotated class collects the whole form body; a `__from_request__` classmethod customizes construction. A missing required param is a 400, a failed cast a 404. These special names need no annotation:\n", + "Handler parameters are filled from the request: each is looked up in path, cookie, header (snake_case names match Hyphen-Case headers), query, then form data (use `Annotated[T, Alias('name')]` to read a different request name), and cast by calling its annotation on the value. Hyphens in form/query names match underscores in handler parameters and typed body fields. Exact names take precedence within each source. Dictionary and request access retain the original keys. `bool`, `int`, and `date` get smart string parsing; `UploadFile` passes through. Repeated params take the last value unless annotated `list[T]`, which collects them all. A param with no annotation and no special name is ignored, with a warning. A dataclass, TypedDict, namedtuple, or any annotated class collects the whole form body; a `__from_request__` classmethod customizes construction. A missing required param is a 400, a failed cast a 404. These special names need no annotation:\n", "\n", " req, ws the Request / WebSocket connection\n", " sess session dict\n", @@ -64,30 +61,26 @@ "`before`/`after` functions (app-level, with `Beforeware` skip patterns, or per-route `before=`) get the same param injection as handlers. A `before` returning a value responds with it and skips the handler (the usual auth-guard pattern).\n", "\n", "See the [Handling Handlers tutorial](https://www.fastht.ml/docs/ref/handlers.html.md) for worked examples of the above." - ] + ], + "id": "ab4062d704000f87" }, { - "cell_type": "markdown", - "id": "46e2e6e8", "metadata": {}, - "source": [ - "This is the source code to fasthtml. You won't need to read this unless you want to understand how things are built behind the scenes, or need full details of a particular API. The notebook is converted to the Python module [fasthtml/core.py](https://github.com/AnswerDotAI/fasthtml/blob/main/fasthtml/core.py) using [nbdev](https://nbdev.fast.ai/)." - ] + "cell_type": "markdown", + "source": "This is the source code to fasthtml. You won't need to read this unless you want to understand how things are built behind the scenes, or need full details of a particular API. The notebook is converted to the Python module [fasthtml/core.py](https://github.com/AnswerDotAI/fasthtml/blob/main/fasthtml/core.py) using [nbdev](https://nbdev.fast.ai/).", + "id": "1acd20a02bd6d35a" }, { - "cell_type": "markdown", - "id": "568b20cd", "metadata": {}, - "source": [ - "## Imports and utils" - ] + "cell_type": "markdown", + "source": "## Imports and utils", + "id": "34bfc48a8b184299" }, { - "cell_type": "code", - "execution_count": null, - "id": "23503b9e", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "#| export\n", "import json,uuid,inspect,types,asyncio,inspect,random,contextlib,itsdangerous,hashlib,signal,subprocess\n", @@ -99,7 +92,7 @@ "from fastcore.style import S\n", "\n", "from types import UnionType, SimpleNamespace as ns, GenericAlias\n", - "from typing import get_args, get_origin, Union, Mapping, List, Any, Callable\n", + "from typing import get_args, get_origin, Union, Mapping, List, Any, Callable, Annotated\n", "from datetime import datetime,date\n", "from dataclasses import dataclass\n", "from inspect import Parameter,get_annotations\n", @@ -116,14 +109,14 @@ "\n", "from fasthtml.starlette import *\n", "from python_multipart.exceptions import MultipartParseError" - ] + ], + "id": "53afb6589c3d143e" }, { - "cell_type": "code", - "execution_count": null, - "id": "7f5d0a72", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "import time, tempfile\n", "\n", @@ -137,125 +130,84 @@ "from fastcore.test import *\n", "from fastcore.net import run_sync\n", "from starlette.datastructures import UploadFile" - ] + ], + "id": "7410b06288e1fe26" }, { - "cell_type": "code", - "execution_count": null, - "id": "19d3f2a7", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "#| export\n", "def _params(f): return signature_ex(f, True).parameters\n", "\n", "empty = Parameter.empty" - ] + ], + "id": "43c1dfb348886a28" }, { - "cell_type": "markdown", - "id": "19ffa7e0", "metadata": {}, - "source": [ - "We write source code _first_, and then tests come _after_. The tests serve as both a means to confirm that the code works and also serves as working examples. The first exported function, `parsed_date`, is an example of this pattern." - ] + "cell_type": "markdown", + "source": "We write source code _first_, and then tests come _after_. The tests serve as both a means to confirm that the code works and also serves as working examples. The first exported function, `parsed_date`, is an example of this pattern.", + "id": "994c8a6af6a4d489" }, { - "cell_type": "code", - "execution_count": null, - "id": "e68a76c9", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "#| export\n", "def parsed_date(s:str):\n", " \"Convert `s` to a datetime\"\n", " return dtparse.parse(s)" - ] + ], + "id": "459b5fc44b7c9d5e" }, { + "metadata": {}, "cell_type": "code", + "outputs": [], "execution_count": null, - "id": "5331a3e7", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "datetime.datetime(2026, 3, 30, 14, 0)" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "parsed_date('2pm')" - ] + "source": "parsed_date('2pm')", + "id": "809da9c50103c9dd" }, { + "metadata": {}, "cell_type": "code", + "outputs": [], "execution_count": null, - "id": "c40c9071", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "True" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "isinstance(date.fromtimestamp(0), date)" - ] + "source": "isinstance(date.fromtimestamp(0), date)", + "id": "5e5a75f6663c14e2" }, { - "cell_type": "code", - "execution_count": null, - "id": "7c820373", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "#| export\n", "def snake2hyphens(s:str):\n", " \"Convert `s` from snake case to hyphenated and capitalised\"\n", " s = snake2camel(s)\n", " return camel2words(s, '-')" - ] + ], + "id": "fd499ac1bf5ca80c" }, { + "metadata": {}, "cell_type": "code", + "outputs": [], "execution_count": null, - "id": "442a5aac", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "'Snake-Case'" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "snake2hyphens(\"snake_case\")" - ] + "source": "snake2hyphens(\"snake_case\")", + "id": "788eebb4a93cd144" }, { - "cell_type": "code", - "execution_count": null, - "id": "25f3b8f8", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "#| export\n", "htmx_hdrs = dict(\n", @@ -281,14 +233,14 @@ "def _get_htmx(h):\n", " res = {k:h.get(v.lower(), None) for k,v in htmx_hdrs.items()}\n", " return HtmxHeaders(**res)" - ] + ], + "id": "5c5266880608b6d1" }, { - "cell_type": "code", - "execution_count": null, - "id": "5b4b5d95", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "def test_request(url: str='/', headers: dict=None, method: str='get')->Request:\n", " if headers is None: headers={}\n", @@ -296,66 +248,53 @@ " client=('127.0.0.1', 8000), server=('127.0.0.1', 8000))\n", " async def receive(): return dict(type=\"http.request\", body=b\"\", more_body=False)\n", " return Request(scope, receive)" - ] + ], + "id": "a223b8b2def6c12f" }, { + "metadata": {}, "cell_type": "code", + "outputs": [], "execution_count": null, - "id": "36e2cac0", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "HtmxHeaders(boosted=None, current_url=None, history_restore_request=None, prompt=None, request='1', request_type=None, source=None, target=None, trigger_name=None, trigger=None)" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], "source": [ "h = test_request(headers=Headers({'HX-Request':'1'}))\n", "_get_htmx(h.headers)" - ] + ], + "id": "76cb9df3f9560f26" }, { - "cell_type": "code", - "execution_count": null, - "id": "1d53e8e7", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "#| export\n", "def _mk_list(t, v): return [t(o) for o in listify(v)]" - ] + ], + "id": "72e3945ec1dcb7ed" }, { - "cell_type": "markdown", - "id": "ef18f76b", "metadata": {}, - "source": [ - "## Request and response" - ] + "cell_type": "markdown", + "source": "## Request and response", + "id": "13f0432b5d256410" }, { - "cell_type": "code", - "execution_count": null, - "id": "5ab74473", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "#| export\n", "fh_cfg = AttrDict(indent=True)" - ] + ], + "id": "64dbed7ee2309943" }, { - "cell_type": "code", - "execution_count": null, - "id": "88d12e68", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "#| export\n", "_special_names = {'ws','request','session','scope','data','htmx','app','state','auth','send','api','body','hdrs','ftrs','bodykw','htmlkw','resp','self'}\n", @@ -364,14 +303,14 @@ " \"Check for common annotation issues; returns warning string or None\"\n", " if anno is empty and arg.lower() not in _special_names and not any(s.startswith(arg.lower()) for s in ('request','session')): return f\"`{arg}` has no type annotation and is not a recognised special name, so is ignored.\"\n", " if isinstance(anno, type) and not get_origin(anno) and issubclass(anno, (list, tuple)) and not _is_body(anno): return f\"`{arg}` uses bare `{anno.__name__}` annotation, so is ignored (use e.g. `{anno.__name__}[str]` instead).\"" - ] + ], + "id": "174eac262617a991" }, { - "cell_type": "code", - "execution_count": null, - "id": "0afb520c", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "#| export\n", "def _fix_anno(t, o):\n", @@ -385,14 +324,14 @@ " if isinstance(t, type) and issubclass(t, (list,tuple)): return None\n", " if not isinstance(o, (str,list,tuple)): return o\n", " return res(o[-1]) if isinstance(o,(list,tuple)) else res(o)" - ] + ], + "id": "b61bf0b9981ede39" }, { - "cell_type": "code", - "execution_count": null, - "id": "95b1f5c9", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "test_eq(_fix_anno(Union[str,None], 'a'), 'a')\n", "test_eq(_fix_anno(float, 0.9), 0.9)\n", @@ -406,14 +345,14 @@ "test_eq(_fix_anno(tuple, ['1','2']), None)\n", "test_eq(_fix_anno(list[str], []), [])\n", "test_eq(_fix_anno(Optional[list[str]], '1'), ['1'])" - ] + ], + "id": "1734c816b8331d79" }, { - "cell_type": "code", - "execution_count": null, - "id": "c58ccadb", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "#| export\n", "def _form_arg(k, v, d):\n", @@ -424,76 +363,63 @@ " anno = d.get(k, None)\n", " if not anno: return v\n", " return _fix_anno(anno, v)" - ] + ], + "id": "d1cd459b43ebdeb8" }, { - "cell_type": "code", - "execution_count": null, - "id": "59757d76", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "d = dict(k=int, l=List[int])\n", "test_eq(_form_arg('k', \"1\", d), 1)\n", "test_eq(_form_arg('l', \"1\", d), [1])\n", "test_eq(_form_arg('l', [\"1\",\"2\"], d), [1,2])" - ] + ], + "id": "c56632e237956f69" }, { - "cell_type": "code", - "execution_count": null, - "id": "5fc04751", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "#| export\n", "@dataclass\n", "class HttpHeader:\n", " \"A response header as a k,v pair\"\n", " k:str;v:str" - ] + ], + "id": "e02eb8ef77a0ed27" }, { - "cell_type": "code", - "execution_count": null, - "id": "94e18161", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "#| export\n", "def _to_htmx_header(s): return 'HX-' + s.replace('_', '-').title()\n", "\n", "htmx_resps = dict(location=None, push_url=None, redirect=None, refresh=None, replace_url=None,\n", " reswap=None, retarget=None, reselect=None, trigger=None, trigger_after_settle=None, trigger_after_swap=None)" - ] + ], + "id": "20c90293417cb2af" }, { + "metadata": {}, "cell_type": "code", + "outputs": [], "execution_count": null, - "id": "592d6c8e", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "'HX-Trigger-After-Settle'" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "_to_htmx_header('trigger_after_settle')" - ] + "source": "_to_htmx_header('trigger_after_settle')", + "id": "64616ebfdd4b64bb" }, { - "cell_type": "code", - "execution_count": null, - "id": "f6a2e62e", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "#| export\n", "@use_kwargs_dict(**htmx_resps)\n", @@ -501,105 +427,70 @@ " \"HTMX response headers\"\n", " res = tuple(HttpHeader(_to_htmx_header(k), v) for k,v in kwargs.items())\n", " return res[0] if len(res)==1 else res" - ] + ], + "id": "96914eebba4f02bc" }, { + "metadata": {}, "cell_type": "code", + "outputs": [], "execution_count": null, - "id": "e89857eb", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "HttpHeader(k='HX-Trigger-After-Settle', v='hi')" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "HtmxResponseHeaders(trigger_after_settle='hi')" - ] + "source": "HtmxResponseHeaders(trigger_after_settle='hi')", + "id": "2189b2baeb94dd0d" }, { - "cell_type": "code", - "execution_count": null, - "id": "56cc589f", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "#| export\n", "def _annotations(anno):\n", " \"Same as `get_annotations`, but also works on namedtuples\"\n", " if is_namedtuple(anno): return {o:str for o in anno._fields}\n", " return get_annotations(anno)" - ] + ], + "id": "d91ef3bd135dc3ee" }, { + "metadata": {}, "cell_type": "code", + "outputs": [], "execution_count": null, - "id": "5453a684", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "{'a': int, 'b': str}" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], "source": [ "@dataclass\n", "class Foo: a:int; b:str\n", "_annotations(Foo)" - ] + ], + "id": "d4be2f3056e3f950" }, { + "metadata": {}, "cell_type": "code", + "outputs": [], "execution_count": null, - "id": "bcad3a5a", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "{'x': str, 'y': str}" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], "source": [ "Point = namedtuple('Point', ['x', 'y'])\n", "_annotations(Point)" - ] + ], + "id": "d2afd93effac57ad" }, { - "cell_type": "code", - "execution_count": null, - "id": "cb4ed4aa", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "#| export\n", "def _is_body(anno): return issubclass(anno, (dict,ns)) or hasattr(anno,'__from_request__') or _annotations(anno)" - ] + ], + "id": "ffd54d552801d9a5" }, { - "cell_type": "code", - "execution_count": null, - "id": "ffdde66f", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "#| export\n", "def _formitem(form, k):\n", @@ -608,53 +499,53 @@ " if isinstance(form, dict): return form.get(k)\n", " o = form.getlist(k)\n", " return o[0] if len(o) == 1 else o if o else None" - ] + ], + "id": "9008844db08f88f2" }, { - "cell_type": "code", - "execution_count": null, - "id": "5fe74444", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "#| export\n", "def form2dict(form: FormData) -> dict:\n", " \"Convert starlette form data to a dict\"\n", " if isinstance(form, dict): return form\n", " return {k: _formitem(form, k) for k in form}" - ] + ], + "id": "cff090e30c5ca11a" }, { - "cell_type": "code", - "execution_count": null, - "id": "cf80ea34", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "d = [('a',1),('a',2),('b',0)]\n", "fd = FormData(d)\n", "res = form2dict(fd)\n", "test_eq(res['a'], [1,2])\n", "test_eq(res['b'], 0)" - ] + ], + "id": "8e046d5aa0ad19ec" }, { - "cell_type": "code", - "execution_count": null, - "id": "8899bc0a", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "#| export\n", "DEF_MAXPART = 100*1024*1024" - ] + ], + "id": "319a6c62cc3e35ed" }, { - "cell_type": "code", - "execution_count": null, - "id": "42c9cea0", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "#| export\n", "async def parse_form(req: Request) -> FormData:\n", @@ -674,50 +565,48 @@ " if not isinstance(res, dict): raise HTTPException(400, \"JSON body must be an object\")\n", " return res\n", " return await req.form(max_part_size=maxpart)" - ] + ], + "id": "9c5cdcc778cc38a7" }, { - "cell_type": "markdown", - "id": "437263a3", "metadata": {}, - "source": [ - "Use the special `__from_request__` class method for custom creation:" - ] + "cell_type": "markdown", + "source": "Use the special `__from_request__` class method for custom creation:", + "id": "af8b65337d831e72" }, { - "cell_type": "code", - "execution_count": null, - "id": "8235f17f", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "class Foo(BasicRepr):\n", " def __init__(self, d): self.d = d\n", "\n", " @classmethod\n", " def __from_request__(cls, data, req): return cls(data)" - ] + ], + "id": "a9a4f860d46ba408" }, { - "cell_type": "code", - "execution_count": null, - "id": "a4873835", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "p = Parameter('a', Parameter.POSITIONAL_OR_KEYWORD, annotation=Foo)\n", "\n", "req = test_request(method='POST')\n", "async def mock_form(**kwargs): return FormData({'a':1})\n", "req.form = mock_form" - ] + ], + "id": "dd2182af86fb2578" }, { - "cell_type": "code", - "execution_count": null, - "id": "0caedd04", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "#| export\n", "async def _from_body(conn, p, data):\n", @@ -734,14 +623,14 @@ " if d: data = {k.replace('-', '_'):v for k,v in data.items()} | data\n", " cargs = {k: _form_arg(k, v, d) for k, v in data.items() if not d or k in d}\n", " return anno(**cargs)" - ] + ], + "id": "23f9fadd08c3c28c" }, { - "cell_type": "code", - "execution_count": null, - "id": "88b6da3f", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "#| export\n", "class ApiReturn:\n", @@ -751,22 +640,20 @@ " def __init__(self, isapi=False): self.isapi = isapi\n", " def __call__(self, norm=None, **kw): return kw if self.isapi else norm\n", " def __bool__(self): return bool(self.isapi)" - ] + ], + "id": "afa2e38d1b854c81" }, { - "cell_type": "markdown", - "id": "abfc3145", "metadata": {}, - "source": [ - "Routes often need to return different responses depending on whether the request comes from a browser or an API client. The `api:ApiReturn` parameter handles this automatically — add it to any route signature and call it with two arguments: the API response and the browser response. If the request's `Accept` header is `application/json` then a dict of the kwargs is returned, otherwise, the first value is returned. For example, `return api(Redirect('/records'), id=record.id)` returns {'id':id} for API callers and a redirect for the browser. This keeps your route logic in one place instead of splitting it across separate endpoints." - ] + "cell_type": "markdown", + "source": "Routes often need to return different responses depending on whether the request comes from a browser or an API client. The `api:ApiReturn` parameter handles this automatically — add it to any route signature and call it with two arguments: the API response and the browser response. If the request's `Accept` header is `application/json` then a dict of the kwargs is returned, otherwise, the first value is returned. For example, `return api(Redirect('/records'), id=record.id)` returns {'id':id} for API callers and a redirect for the browser. This keeps your route logic in one place instead of splitting it across separate endpoints.", + "id": "ec73cbbd214917ea" }, { - "cell_type": "code", - "execution_count": null, - "id": "7cc39ba9", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "#| export\n", "class JSONResponse(JSONResponseOrig):\n", @@ -775,22 +662,14 @@ " def _default(o): return list(o) if is_listy(o) else str(o)\n", " res = json.dumps(content, ensure_ascii=False, allow_nan=False, indent=None, separators=(\",\",\":\"), default=_default)\n", " return res.encode(\"utf-8\")\n" - ] + ], + "id": "6fc0c7f6b7e307fe" }, { + "metadata": {}, "cell_type": "code", + "outputs": [], "execution_count": null, - "id": "2a8b10f4", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "{'k': 'value1', 'v': 'value3'}\n" - ] - } - ], "source": [ "async def f(req):\n", " def _f(p:HttpHeader): ...\n", @@ -804,14 +683,14 @@ "d = dict(k='value1',v=['value2','value3'])\n", "response = client.post('/', data=d)\n", "print(response.json())" - ] + ], + "id": "91a217829d3e79f9" }, { - "cell_type": "code", - "execution_count": null, - "id": "301e06eb", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "# An empty `application/json` body yields `{}` (like the empty-multipart guard), not a 500\n", "async def _empty_json(req): return JSONResponse(form2dict(await parse_form(req)))\n", @@ -821,84 +700,80 @@ "test_eq(res.json(), {})\n", "res = client.post('/', json={'a':1}) # non-empty json still parses (behavior preserved)\n", "test_eq(res.json(), {'a':1})" - ] + ], + "id": "126d0dcf0eb89218" }, { - "cell_type": "markdown", - "id": "18a9e366", "metadata": {}, - "source": [ - "A malformed multipart body (here the opening boundary isn't followed by CRLF) is the client's error, so `parse_form` answers 400 rather than letting the parser's exception surface as a 500:" - ] + "cell_type": "markdown", + "source": "A malformed multipart body (here the opening boundary isn't followed by CRLF) is the client's error, so `parse_form` answers 400 rather than letting the parser's exception surface as a 500:", + "id": "bd7f8488c0910f52" }, { - "cell_type": "code", - "execution_count": null, - "id": "28bfbbc1", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "bad = b'--xyzXX\\r\\nContent-Disposition: form-data; name=\"a\"\\r\\n\\r\\n1\\r\\n--xyz--\\r\\n'\n", "res = client.post('/', content=bad, headers={'content-type':'multipart/form-data; boundary=xyz'})\n", "test_eq(res.status_code, 400)\n", "res.text" - ] + ], + "id": "71c4ef54948643a3" }, { - "cell_type": "markdown", - "id": "6103784b", "metadata": {}, - "source": [ - "A JSON body that does not decode, or decodes to something other than an object (an array, say), cannot supply route parameters, so it is refused with 400 rather than failing inside the form conversion:" - ] + "cell_type": "markdown", + "source": "A JSON body that does not decode, or decodes to something other than an object (an array, say), cannot supply route parameters, so it is refused with 400 rather than failing inside the form conversion:", + "id": "f785db5c4a5d10f2" }, { - "cell_type": "code", - "execution_count": null, - "id": "2aaa8fbe", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "res = client.post('/', json=[1,2])\n", "test_eq(res.status_code, 400)\n", "res = client.post('/', content=b'not json', headers={'content-type':'application/json'})\n", "test_eq(res.status_code, 400)\n", "res.text" - ] + ], + "id": "2079e9d02dd2e49c" }, { + "metadata": {}, "cell_type": "code", + "outputs": [], "execution_count": null, - "id": "9246153f", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "\"['1', '2']\"" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], "source": [ "async def f(req): return Response(str(req.query_params.getlist('x')))\n", "client = TestClient(Starlette(routes=[Route('/', f, methods=['GET'])]))\n", "client.get('/?x=1&x=2').text" - ] + ], + "id": "bc54b0a9ba395e42" }, { - "cell_type": "code", - "execution_count": null, - "id": "5fa96e3a", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "#| export\n", + "@dataclass(frozen=True)\n", + "class Alias:\n", + " \"Read a handler param from request data under `name` instead of its Python name, e.g. `Annotated[str, Alias('user-id')]`\"\n", + " name: str\n", + "\n", "async def _find_p(conn, data, hdrs, arg:str, p:Parameter):\n", " \"In `data` find param named `arg` of type in `p` (`arg` is ignored for body types)\"\n", + " alias = None\n", + " if get_origin(p.annotation) is Annotated:\n", + " anno, *meta = get_args(p.annotation)\n", + " p = p.replace(annotation=anno)\n", + " alias = next((m.name for m in meta if isinstance(m, Alias)), None)\n", + " key = alias or arg\n", " anno = p.annotation\n", " # Special annotation types\n", " if isinstance(anno, type) and not isinstance(anno, GenericAlias):\n", @@ -929,85 +804,66 @@ " if arg.lower() in ('hdrs','ftrs','bodykw','htmlkw'): return getattr(conn, arg.lower())\n", " return None\n", " # Not a special name or a special annotation\n", - " res = conn.path_params.get(arg, None)\n", - " if res in (empty,None): res = conn.cookies.get(arg, None)\n", + " res = conn.path_params.get(key, None)\n", + " if res in (empty,None): res = conn.cookies.get(key, None)\n", " if res in (empty,None): res = hdrs.get(snake2hyphens(arg), None)\n", - " if res in (empty,None): res = _formitem(conn.query_params, arg)\n", - " if res in (empty,None): res = _formitem(data, arg)\n", - " if res in (empty,None) and isinstance(vals := data.get('values'), dict): res = _formitem(vals, arg) # htmx v4 nests form data under `values`\n", + " if res in (empty,None): res = _formitem(conn.query_params, key)\n", + " if res in (empty,None): res = _formitem(data, key)\n", + " if res in (empty,None) and isinstance(vals := data.get('values'), dict): res = _formitem(vals, key) # htmx v4 nests form data under `values`\n", " if res in (empty,None):\n", " if p.default is empty:\n", - " if isinstance(conn, Request): raise HTTPException(400, f\"Missing required field: {arg}\")\n", - " raise ValueError(f\"Missing required field: {arg}\")\n", + " if isinstance(conn, Request): raise HTTPException(400, f\"Missing required field: {key}\")\n", + " raise ValueError(f\"Missing required field: {key}\")\n", " res = p.default\n", " try: return _fix_anno(anno, res)\n", " except ValueError as e:\n", " if isinstance(conn, Request): raise HTTPException(404, f\"{conn.url.path}: {e}\") from None\n", " raise" - ] + ], + "id": "8e679f81c025a2e6" }, { - "cell_type": "code", - "execution_count": null, - "id": "bf42edad", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "#| export\n", "async def _find_ps(conn, data, hdrs, params):\n", " if conn.query_params: data |= dict(conn.query_params)\n", " return {arg:await _find_p(conn, data, hdrs, arg, p) for arg,p in params.items()}" - ] + ], + "id": "d98c2374a04c1424" }, { + "metadata": {}, "cell_type": "code", + "outputs": [], "execution_count": null, - "id": "0ac66d98", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "Foo(d={'a': 1})" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], "source": [ "data = form2dict(await parse_form(req))\n", "await _from_body(req, p, data)" - ] + ], + "id": "1895949b223f331d" }, { - "cell_type": "code", - "execution_count": null, - "id": "090f1f0f", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "#| export\n", "async def _wrap_req(req, params):\n", " data = form2dict(await parse_form(req))\n", " return await _find_ps(req, data, req.headers, params)" - ] + ], + "id": "e5f9b252b5404d6" }, { + "metadata": {}, "cell_type": "code", + "outputs": [], "execution_count": null, - "id": "26df5218", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "ok body=19\n" - ] - } - ], "source": [ "def g(test_val:int=0, item:HttpHeader=None, htmx:HtmxHeaders=None, api:ApiReturn=None): ...\n", "\n", @@ -1020,22 +876,14 @@ "r = client.post('/', data=dict(test_val='21', k='a', v='b'), headers={'HX-Request': '1'})\n", "test_eq(r.status_code, 200)\n", "print(r.text)" - ] + ], + "id": "212c21983334789e" }, { + "metadata": {}, "cell_type": "code", + "outputs": [], "execution_count": null, - "id": "bf945ee8", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "{'req': , 'this': , 'a': '1', 'b': HttpHeader(k='value1', v='value3'), 'state': }\n" - ] - } - ], "source": [ "def g(req, this:Starlette, a:str, b:HttpHeader, state): ...\n", "\n", @@ -1046,22 +894,14 @@ "client = TestClient(Starlette(routes=[Route('/', f, methods=['POST'])]))\n", "response = client.post('/?a=1', data=d)\n", "print(response.text)" - ] + ], + "id": "3aab2026066508b8" }, { + "metadata": {}, "cell_type": "code", + "outputs": [], "execution_count": null, - "id": "a3ded5ec", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "{'req': , 'this': , 'a': '1', 'b': HttpHeader(k='value1', v='value3')}\n" - ] - } - ], "source": [ "def g(req, this:Starlette, a:str, b:HttpHeader): ...\n", "\n", @@ -1072,25 +912,14 @@ "client = TestClient(Starlette(routes=[Route('/', f, methods=['POST'])]))\n", "response = client.post('/?a=1', data=d)\n", "print(response.text)" - ] + ], + "id": "ad76da242022e3f4" }, { + "metadata": {}, "cell_type": "code", + "outputs": [], "execution_count": null, - "id": "0e7601fe", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "\"Bar(accept='application/json')\"" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], "source": [ "class Bar(BasicRepr):\n", " @classmethod\n", @@ -1105,38 +934,26 @@ "\n", "client = TestClient(Starlette(routes=[Route('/', f, methods=['POST'])]))\n", "client.post('/', headers={'Accept': 'application/json'}).text" - ] + ], + "id": "ead1df177cd0001" }, { - "cell_type": "markdown", - "id": "34066c89", "metadata": {}, - "source": [ - "**Missing Request Params**" - ] + "cell_type": "markdown", + "source": "**Missing Request Params**", + "id": "db783b911aea310d" }, { - "cell_type": "markdown", - "id": "06259883", "metadata": {}, - "source": [ - "If a request param has a default value (e.g. `a:str=''`), the request is valid even if the user doesn't include the param in their request." - ] + "cell_type": "markdown", + "source": "If a request param has a default value (e.g. `a:str=''`), the request is valid even if the user doesn't include the param in their request.", + "id": "8774cb8b857934eb" }, { + "metadata": {}, "cell_type": "code", + "outputs": [], "execution_count": null, - "id": "c369a89c", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "{'req': , 'this': , 'a': ''}\n" - ] - } - ], "source": [ "def g(req, this:Starlette, a:str=''): ...\n", "\n", @@ -1147,30 +964,20 @@ "client = TestClient(Starlette(routes=[Route('/', f, methods=['POST'])]))\n", "response = client.post('/', json={}) # no param in request\n", "print(response.text)" - ] + ], + "id": "624c7f99944813aa" }, { - "cell_type": "markdown", - "id": "35b68f4f", "metadata": {}, - "source": [ - "If we remove the default value and re-run the request, we should get the following error `Missing required field: a`." - ] + "cell_type": "markdown", + "source": "If we remove the default value and re-run the request, we should get the following error `Missing required field: a`.", + "id": "83ffd4d5f69ee8e3" }, { + "metadata": {}, "cell_type": "code", + "outputs": [], "execution_count": null, - "id": "b33b43a7", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Missing required field: a\n" - ] - } - ], "source": [ "def g(req, this:Starlette, a:str): ...\n", "\n", @@ -1181,14 +988,14 @@ "client = TestClient(Starlette(routes=[Route('/', f, methods=['POST'])]))\n", "response = client.post('/', json={}) # no param in request\n", "print(response.text)" - ] + ], + "id": "454d528731449c" }, { - "cell_type": "code", - "execution_count": null, - "id": "7a661bfa", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "#| export\n", "def flat_xt(lst):\n", @@ -1199,85 +1006,83 @@ " if isinstance(item, (list,tuple)): result.extend(item)\n", " else: result.append(item)\n", " return tuple(result)" - ] + ], + "id": "693922c3e46c7754" }, { - "cell_type": "code", - "execution_count": null, - "id": "2ee5adf1", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "x = ft('a',1)\n", "test_eq(flat_xt([x, x, [x,x]]), (x,)*4)\n", "test_eq(flat_xt(x), (x,))" - ] + ], + "id": "581fbbf507982aae" }, { - "cell_type": "code", - "execution_count": null, - "id": "aacff5ac", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "#| export\n", "class Beforeware:\n", " \"Wrap a `before` function with `skip` path patterns that bypass it\"\n", " def __init__(self, f, skip=None): self.f,self.skip = f,skip or []\n", " def __repr__(self): return f'Beforeware({self.f}, skip={self.skip})'" - ] + ], + "id": "6192cec3c0df1bb3" }, { - "cell_type": "code", - "execution_count": null, - "id": "78c3c357", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "#| export\n", "async def _handle(f, /, *args, **kwargs):\n", " return (await f(*args, **kwargs)) if is_async_callable(f) else await run_in_threadpool(f, *args, **kwargs)" - ] + ], + "id": "8ec98475a0a5c7d6" }, { - "cell_type": "code", - "execution_count": null, - "id": "c995850c", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "async def _f(f): return f\"got {f}\"\n", "test_eq(await _handle(_f, f='hello'), 'got hello')" - ] + ], + "id": "da268ae91d91d9bc" }, { - "cell_type": "markdown", - "id": "079a3215", "metadata": {}, - "source": [ - "## Websockets / SSE" - ] + "cell_type": "markdown", + "source": "## Websockets / SSE", + "id": "92d3135c4ad6710f" }, { - "cell_type": "code", - "execution_count": null, - "id": "ad0f0e87", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "#| export\n", "async def _wrap_ws(ws, data, params):\n", " raw = data.pop('HEADERS', {}) or (data.pop('headers') if isinstance(data.get('headers'), dict) else {}) # htmx v4 sends lowercase `headers`\n", " hdrs = Headers({k.lower():v for k,v in raw.items() if v is not None})\n", " return await _find_ps(ws, data, hdrs, params)" - ] + ], + "id": "5f2702274bb51006" }, { - "cell_type": "code", - "execution_count": null, - "id": "dcc15129", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "#| export\n", "async def _send_ws(ws, resp):\n", @@ -1306,14 +1111,14 @@ " if disconn: cls.on_disconnect = _disconnect\n", " cls.on_receive = _recv\n", " return cls" - ] + ], + "id": "9419cd0224cd98c2" }, { - "cell_type": "code", - "execution_count": null, - "id": "983bcfe2", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "def on_receive(msg:str): return f\"Message text was: {msg}\"\n", "c = _ws_endp(on_receive)\n", @@ -1322,14 +1127,14 @@ " ws.send_text('{\"msg\":\"Hi!\"}')\n", " data = ws.receive_text()\n", " assert data == 'Message text was: Hi!', data" - ] + ], + "id": "bc7c575a83684d5b" }, { - "cell_type": "code", - "execution_count": null, - "id": "bda2e425", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "def on_receive(hx_trigger:str): return f\"trigger: {hx_trigger}\"\n", "cli = TestClient(Starlette(routes=[WebSocketRoute('/', _ws_endp(on_receive))]))\n", @@ -1337,27 +1142,27 @@ " ws.send_text(json.dumps({\"HEADERS\": {\"Hx-Trigger\": \"my-btn\"}}))\n", " data = ws.receive_text()\n", " assert data == 'trigger: my-btn', data\n" - ] + ], + "id": "42a74b181d3b6a8f" }, { - "cell_type": "code", - "execution_count": null, - "id": "5b0e7677", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "#| export\n", "def EventStream(s):\n", " \"Create a text/event-stream response from `s`\"\n", " return StreamingResponse(s, media_type=\"text/event-stream\")" - ] + ], + "id": "741044b3e551225c" }, { - "cell_type": "code", - "execution_count": null, - "id": "0dd0a414", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "#| export\n", "def signal_shutdown():\n", @@ -1370,60 +1175,58 @@ " self.force_exit = True\n", " self._orig_handle_exit(*args, **kwargs)\n", " return event" - ] + ], + "id": "da2d506cff9cd847" }, { - "cell_type": "markdown", - "id": "496cd78f", "metadata": {}, - "source": [ - "## Routing and application" - ] + "cell_type": "markdown", + "source": "## Routing and application", + "id": "a4eeb45c2f82f3ff" }, { - "cell_type": "code", - "execution_count": null, - "id": "03f4c639", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "#| export\n", "def uri(_arg, **kwargs):\n", " \"Create a URI by URL-encoding `_arg` and appending query parameters from `kwargs`\"\n", " return f\"{quote(_arg)}/{urlencode(kwargs, doseq=True)}\"" - ] + ], + "id": "184283f3ee5d49ba" }, { - "cell_type": "code", - "execution_count": null, - "id": "bdb2ac14", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "#| export\n", "def decode_uri(s):\n", " \"Decode a URI created by `uri()` back into argument and keyword dict\"\n", " arg,_,kw = s.partition('/')\n", " return unquote(arg), {k:v[0] for k,v in parse_qs(kw).items()}" - ] + ], + "id": "ccfedf12c80ff96" }, { - "cell_type": "code", - "execution_count": null, - "id": "b80ce139", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "#| export\n", "from starlette.convertors import StringConvertor" - ] + ], + "id": "fd09bc5e426f4a9c" }, { - "cell_type": "code", - "execution_count": null, - "id": "a27adc1e", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "#| export\n", "StringConvertor.regex = \"[^/]*\" # `+` replaced with `*`\n", @@ -1434,28 +1237,28 @@ " assert \"/\" not in value, \"May not contain path separators\"\n", " # assert value, \"Must not be empty\" # line removed due to errors\n", " return value" - ] + ], + "id": "7b7ad4249ea81211" }, { - "cell_type": "code", - "execution_count": null, - "id": "46614165", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "#| export\n", "@patch\n", "def url_path_for(self:HTTPConnection, name: str, **path_params):\n", " lp = self.scope['app'].url_path_for(name, **path_params)\n", " return URLPath(f\"{self.scope['root_path']}{lp}\", lp.protocol, lp.host)" - ] + ], + "id": "70c8ec8b0a8ab19f" }, { - "cell_type": "code", - "execution_count": null, - "id": "c1707d59", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "#| export\n", "_verbs = dict(get='hx-get', post='hx-post', put='hx-put', delete='hx-delete', patch='hx-patch', link='href')\n", @@ -1482,25 +1285,25 @@ " \"Convert response to XML string with target URL resolution\"\n", " _find_targets(req, resp)\n", " return to_xml(resp, indent=indent)" - ] + ], + "id": "3f97f1ed8c754dff" }, { - "cell_type": "code", - "execution_count": null, - "id": "f1e3ed2d", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "#| export\n", "_iter_typs = (tuple,list,map,filter,range,types.GeneratorType)" - ] + ], + "id": "fb23ee8a4bdf6ffc" }, { - "cell_type": "code", - "execution_count": null, - "id": "a407dc0e", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "#| export\n", "def flat_tuple(o):\n", @@ -1512,27 +1315,27 @@ " if isinstance(item, _iter_typs): result.extend(list(item))\n", " else: result.append(item)\n", " return tuple(result)" - ] + ], + "id": "f729e85becb6bbb6" }, { - "cell_type": "code", - "execution_count": null, - "id": "d36402e6", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "#| export\n", "def noop_body(c, req):\n", " \"Default Body wrap function which just returns the content\"\n", " return c" - ] + ], + "id": "3e5a0b56fa0c4857" }, { - "cell_type": "code", - "execution_count": null, - "id": "7f49728d", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "#| export\n", "def respond(req, heads, bdy):\n", @@ -1542,37 +1345,37 @@ " bw_args = (bdy, req) if len(params)>1 else (bdy,)\n", " body = Body(body_wrap(*bw_args), *flat_xt(req.ftrs), **req.bodykw)\n", " return Html(Head(*heads, *flat_xt(req.hdrs)), body, **req.htmlkw)" - ] + ], + "id": "b8e014df4ebb00b3" }, { - "cell_type": "markdown", - "id": "cfae0a56", "metadata": {}, + "cell_type": "markdown", "source": [ "Render fragment if `HX-Request` header is _present_ and\n", " `HX-History-Restore-Request` header is _absent._" - ] + ], + "id": "c42f6fb487aceee5" }, { - "cell_type": "code", - "execution_count": null, - "id": "b2007479", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "#| export\n", "def is_full_page(req, resp):\n", " \"Check if response should be rendered as full page or fragment\"\n", " if resp and any(getattr(o, 'tag', '')=='html' for o in resp): return True\n", " return 'hx-request' in req.headers and 'hx-history-restore-request' not in req.headers" - ] + ], + "id": "7ba6db1142901c4d" }, { - "cell_type": "code", - "execution_count": null, - "id": "358badec", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "#| export\n", "def _part_resp(req, resp):\n", @@ -1590,14 +1393,14 @@ " resp = tuple(resp)\n", " if len(resp)==1: resp = resp[0]\n", " return resp,kw" - ] + ], + "id": "58f36aba629b2268" }, { - "cell_type": "code", - "execution_count": null, - "id": "da449a7b", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "#| export\n", "def _canonical(req):\n", @@ -1614,27 +1417,27 @@ " title = [] if any(getattr(o, 'tag', '')=='title' for o in heads) else [Title(req.app.title)]\n", " resp = respond(req, [*heads, *title, *_canonical(req)], bdy)\n", " return _to_xml(req, resp, indent=fh_cfg.indent)" - ] + ], + "id": "a005b335ea8a4c04" }, { - "cell_type": "code", - "execution_count": null, - "id": "775fb66b", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "#| export\n", "def _is_ft_resp(resp):\n", " \"Check if response is a FastTag-compatible type\"\n", " return isinstance(resp, _iter_typs+(HttpHeader,FT)) or hasattr(resp, '__ft__')" - ] + ], + "id": "73c48c2cb1072a7e" }, { - "cell_type": "code", - "execution_count": null, - "id": "968d9245", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "#| export\n", "def _resp(req, resp, cls=empty, status_code=200):\n", @@ -1655,14 +1458,14 @@ " resp = str(resp)\n", " cls = HTMLResponse\n", " return cls(resp, status_code=status_code, **kw)" - ] + ], + "id": "7c02e80fed13238e" }, { - "cell_type": "code", - "execution_count": null, - "id": "eac44461", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "#| export\n", "class Redirect:\n", @@ -1671,28 +1474,28 @@ " def __response__(self, req):\n", " if 'hx-request' in req.headers: return HtmxResponseHeaders(redirect=self.loc)\n", " return RedirectResponse(self.loc, status_code=303)" - ] + ], + "id": "896b46c4aa03192c" }, { - "cell_type": "code", - "execution_count": null, - "id": "1ba52822", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "#| export\n", "async def _wrap_call(f, req, params):\n", " \"Wrap function call with request parameter injection\"\n", " wreq = await _wrap_req(req, params)\n", " return await _handle(f, **wreq)" - ] + ], + "id": "9b9774380fb5223c" }, { - "cell_type": "code", - "execution_count": null, - "id": "b0d1cbbf", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "#| export\n", "# chkstyle: skip\n", @@ -1713,40 +1516,28 @@ " \"live\": \"https://cdn.jsdelivr.net/npm/htmx.org@4.0.0/dist/ext/hx-live.min.js\",\n", " \"multipart\": \"https://cdn.jsdelivr.net/npm/htmx.org@4.0.0/dist/ext/hx-multipart.min.js\"\n", "}" - ] + ], + "id": "5df474a1953c5134" }, { - "cell_type": "markdown", - "id": "3531273d", "metadata": {}, - "source": [ - "The FastHTML `exts` param supports the following:" - ] + "cell_type": "markdown", + "source": "The FastHTML `exts` param supports the following:", + "id": "d2f9aef7815d59bb" }, { + "metadata": {}, "cell_type": "code", + "outputs": [], "execution_count": null, - "id": "deffbaaa", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "morph head-support preload class-tools loading-states multi-swap path-deps remove-me debug ws chunked-transfer\n" - ] - } - ], - "source": [ - "print(' '.join(htmx_exts))" - ] + "source": "print(' '.join(htmx_exts))", + "id": "fe8fdb5cd2c94da9" }, { - "cell_type": "code", - "execution_count": null, - "id": "60cb52ea", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "#| export\n", "htmxsrc = Script(src=\"https://cdn.jsdelivr.net/npm/htmx.org@2.0.7/dist/htmx.js\")\n", @@ -1756,14 +1547,14 @@ "scopesrc = Script(src=\"https://cdn.jsdelivr.net/gh/gnat/css-scope-inline@main/script.js\")\n", "viewport = Meta(name=\"viewport\", content=\"width=device-width, initial-scale=1, viewport-fit=cover\")\n", "charset = Meta(charset=\"utf-8\")" - ] + ], + "id": "ab5aae7c786f4db0" }, { - "cell_type": "code", - "execution_count": null, - "id": "8bd78eeb", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "#| export\n", "def get_key(key=None, fname='.sesskey'):\n", @@ -1774,27 +1565,27 @@ " key = str(uuid.uuid4())\n", " fname.write_text(key)\n", " return key" - ] + ], + "id": "fd36cd44687c2273" }, { - "cell_type": "code", - "execution_count": null, - "id": "042666e2", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "#| export\n", "def _list(o):\n", " \"Wrap non-list item in a list, returning empty list if None\"\n", " return [] if not o else list(o) if isinstance(o, (tuple,list)) else [o]" - ] + ], + "id": "97ae79dd8df934d9" }, { - "cell_type": "code", - "execution_count": null, - "id": "d276fc71", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "#| export\n", "def _wrap_ex(f, status_code, hdrs, ftrs, htmlkw, bodykw, body_wrap):\n", @@ -1805,14 +1596,14 @@ " res = await _handle(f, req, exc)\n", " return _resp(req, res, status_code=status_code)\n", " return _f" - ] + ], + "id": "440490e465c515b4" }, { - "cell_type": "code", - "execution_count": null, - "id": "bc323fd4", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "#| export\n", "def qp(p:str, **kw) -> str:\n", @@ -1825,63 +1616,57 @@ " p = re.sub(r'\\{([^:}]+)(:.+?)?}', _sub, p)\n", " # encode query params\n", " return p + ('?' + urlencode({k:'' if v in (False,None) else v for k,v in kw.items()},doseq=True) if kw else '')" - ] + ], + "id": "8c482e84ada42852" }, { - "cell_type": "markdown", - "id": "e51e2dc3", "metadata": {}, - "source": [ - "`qp` adds query parameters to route path strings" - ] + "cell_type": "markdown", + "source": "`qp` adds query parameters to route path strings", + "id": "2b1d80a716c0adef" }, { - "cell_type": "code", - "execution_count": null, - "id": "ff82dc78", "metadata": {}, + "cell_type": "code", "outputs": [], - "source": [ - "vals = dict(a=5, b=False, c=[1,2], d='bar', e=None, ab=42)" - ] + "execution_count": null, + "source": "vals = dict(a=5, b=False, c=[1,2], d='bar', e=None, ab=42)", + "id": "54be93910e6e66ba" }, { - "cell_type": "code", - "execution_count": null, - "id": "c0836a8f", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "res = qp('/foo', **vals)\n", "test_eq(res, '/foo?a=5&b=&c=1&c=2&d=bar&e=&ab=42')" - ] + ], + "id": "a7000a851f7ec0b1" }, { - "cell_type": "markdown", - "id": "4740272f", "metadata": {}, - "source": [ - "`qp` checks to see if each param should be sent as a query parameter or as part of the route, and encodes that properly." - ] + "cell_type": "markdown", + "source": "`qp` checks to see if each param should be sent as a query parameter or as part of the route, and encodes that properly.", + "id": "9caeec84af6b57b9" }, { - "cell_type": "code", - "execution_count": null, - "id": "50ebb1ee", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "path = '/foo/{a}/{d}/{ab:int}'\n", "res = qp(path, **vals)\n", "test_eq(res, '/foo/5/bar/42?b=&c=1&c=2&e=')" - ] + ], + "id": "37b1595d560ee414" }, { - "cell_type": "code", - "execution_count": null, - "id": "f86690c4", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "#| export\n", "def def_hdrs(htmx=True, htmx4=False, surreal=True):\n", @@ -1895,14 +1680,14 @@ " # TODO: Check if fhjsscr works with htmx4\n", " elif htmx: hdrs = [htmxsrc,fhjsscr] + hdrs\n", " return [charset, viewport] + hdrs" - ] + ], + "id": "6a347c42c3a0b6b8" }, { - "cell_type": "code", - "execution_count": null, - "id": "2c5285ae", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "#| export\n", "cors_allow = Middleware(CORSMiddleware, allow_credentials=True, allow_origins=['*'], allow_methods=['*'], allow_headers=['*'])\n", @@ -1928,14 +1713,14 @@ " }\n", " };\n", "\"\"\"))\n" - ] + ], + "id": "7de7d4d9ce75b85d" }, { - "cell_type": "code", - "execution_count": null, - "id": "17ced9a3", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "#| export\n", "class _LifespanCtx:\n", @@ -1963,14 +1748,14 @@ " for f in self.shutdown: await _handle(f)\n", "\n", " def on_event(self, event_type): return lambda f: (getattr(self, event_type)).append(f)" - ] + ], + "id": "852e2ec0c0969f52" }, { - "cell_type": "code", - "execution_count": null, - "id": "3327a1e9", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "#| export\n", "class FastHTML(Starlette):\n", @@ -2010,22 +1795,20 @@ " super().__init__(debug, routes, middleware=middleware, exception_handlers=excs, lifespan=self.lifespan)\n", "\n", " def on_event(self, event_type): return self.lifespan.on_event(event_type)" - ] + ], + "id": "8e95f37034125b68" }, { - "cell_type": "markdown", - "id": "c7d4052c", "metadata": {}, - "source": [ - "### Routes" - ] + "cell_type": "markdown", + "source": "### Routes", + "id": "9fc92122a2fa70f2" }, { - "cell_type": "code", - "execution_count": null, - "id": "dce68049", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "#| export\n", "class HostRoute(Route):\n", @@ -2044,22 +1827,14 @@ " def __repr__(self) -> str:\n", " methods = sorted(self.methods or [])\n", " return f\"{self.__class__.__name__}(path={self.path!r}, name={self.name!r}, methods={methods!r}, host={self.host!r})\"" - ] + ], + "id": "fe44229b6931a496" }, { + "metadata": {}, "cell_type": "code", + "outputs": [], "execution_count": null, - "id": "b8823cfe", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "all passed\n" - ] - } - ], "source": [ "app = FastHTML()\n", "app.router.routes = []\n", @@ -2072,22 +1847,14 @@ "test_eq(cli.get('/', headers={'host': 'localhost'}).text, 'main page')\n", "test_eq(cli.get('/', headers={'host': 'auth.example.com'}).text, 'auth page')\n", "print('all passed')" - ] + ], + "id": "3c04fe56abdc47fa" }, { + "metadata": {}, "cell_type": "code", + "outputs": [], "execution_count": null, - "id": "3da46acd", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "all passed\n" - ] - } - ], "source": [ "app.router.routes.append(HostRoute('/hello', lambda _: Response('api hello'), host='api.{parentdom}', methods=['GET'], name='api_hello'))\n", "app.router.routes.append(HostRoute('/hello', lambda _: Response('normal hello'), methods=['GET'], name='hello'))\n", @@ -2096,14 +1863,14 @@ "test_eq(cli.get('/hello', headers={'host': 'mysite.com'}).text, 'normal hello')\n", "test_eq(cli.get('/hello', headers={'host': 'other.mysite.com'}).text, 'normal hello')\n", "print('all passed')" - ] + ], + "id": "654aac80d680d4eb" }, { - "cell_type": "code", - "execution_count": null, - "id": "e0accf76", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "#| export\n", "@patch\n", @@ -2115,25 +1882,25 @@ " ((route.methods is None) or (set(r.methods) == set(route.methods))))]\n", " self.router.routes.append(route)\n", " self.router.routes.sort(key=lambda r: not getattr(r, 'host', None))\n" - ] + ], + "id": "18175f9ddfa24df4" }, { - "cell_type": "code", - "execution_count": null, - "id": "246bd8d1", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "#| export\n", "all_meths = 'get post put delete patch head trace options'.split()" - ] + ], + "id": "c00f976494575cc" }, { - "cell_type": "code", - "execution_count": null, - "id": "26b147ba", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "#| export\n", "@patch\n", @@ -2163,14 +1930,14 @@ " if nr: resp = nr\n", " return _resp(req, resp, sig.return_annotation)\n", " return _f" - ] + ], + "id": "4837ef8ced64c5e0" }, { - "cell_type": "code", - "execution_count": null, - "id": "3818575c", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "#| export\n", "@patch\n", @@ -2181,14 +1948,14 @@ " route.methods = ['ws']\n", " self.add_route(route)\n", " return func" - ] + ], + "id": "154ea30b2e45f577" }, { - "cell_type": "code", - "execution_count": null, - "id": "669e76eb", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "#| export\n", "@patch\n", @@ -2196,28 +1963,28 @@ " \"Add a websocket route at `path`\"\n", " def f(func=noop): return self._add_ws(func, path, conn, disconn, name=name, middleware=middleware)\n", " return f" - ] + ], + "id": "5655582e8b8129c6" }, { - "cell_type": "code", - "execution_count": null, - "id": "j6ete5u68fo", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "#|export\n", "@patch\n", "def add_websocket_route(self:FastHTML, path, func, conn=None, disconn=None, name=None, middleware=None):\n", " \"Add a websocket route at `path` (Starlette-compatible API)\"\n", " return self._add_ws(func, path, conn, disconn, name=name, middleware=middleware)" - ] + ], + "id": "bb318a080450cf8c" }, { - "cell_type": "code", - "execution_count": null, - "id": "919618c3", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "#| export\n", "def _mk_locfunc(f, p, app=None):\n", @@ -2232,61 +1999,50 @@ " def __str__(self): return p\n", "\n", " return _lf()" - ] + ], + "id": "a294e823478edca7" }, { - "cell_type": "code", - "execution_count": null, - "id": "d2ecc738", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "#| export\n", "def nested_name(f):\n", " \"Get name of function `f` using '_' to join nested function names\"\n", " return f.__qualname__.replace('..', '_')" - ] + ], + "id": "ee7941c6d76afd9e" }, { - "cell_type": "code", - "execution_count": null, - "id": "c0f13ece", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "def f():\n", " def g(): ...\n", " return g" - ] + ], + "id": "67a112ba5ba9ed0d" }, { + "metadata": {}, "cell_type": "code", + "outputs": [], "execution_count": null, - "id": "b218f738", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "'f_g'" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], "source": [ "func = f()\n", "nested_name(func)" - ] + ], + "id": "e04010a30af82a09" }, { - "cell_type": "code", - "execution_count": null, - "id": "daafe4fc", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "#| export\n", "@patch\n", @@ -2299,14 +2055,14 @@ " handler = getattr(cls, meth, None)\n", " if handler: self._add_route(handler, path, meth, name, include_in_schema, body_wrap, host=host, before=before)\n", " return lf" - ] + ], + "id": "ebb18855aabae4a3" }, { - "cell_type": "code", - "execution_count": null, - "id": "3710e48b", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "#| export\n", "def _route_pn(func, path, name):\n", @@ -2332,14 +2088,14 @@ " lf = _mk_locfunc(func, p, app=self)\n", " lf.__routename__ = n\n", " return lf" - ] + ], + "id": "ce6f387e5f02d9db" }, { - "cell_type": "code", - "execution_count": null, - "id": "f5cb2c2b", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "#| export\n", "@patch\n", @@ -2350,71 +2106,47 @@ " return f(path) if callable(path) else f\n", "\n", "for o in all_meths: setattr(FastHTML, o, partialmethod(FastHTML.route, methods=o))" - ] + ], + "id": "112b50b015b12164" }, { + "metadata": {}, "cell_type": "code", + "outputs": [], "execution_count": null, - "id": "e6ee3a86", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "'/foo?a=bar&b=1&b=2'" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], "source": [ "app = FastHTML()\n", "@app.get\n", "def foo(a:str, b:list[int]): ...\n", "\n", "foo.to(a='bar', b=[1,2])" - ] + ], + "id": "dff8e8a4a56cf236" }, { + "metadata": {}, "cell_type": "code", + "outputs": [], "execution_count": null, - "id": "9b9f1f03", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "'/foo/bar?b=1&b=2'" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], "source": [ "@app.get('/foo/{a}')\n", "def foo(a:str, b:list[int]): ...\n", "\n", "foo.to(a='bar', b=[1,2])" - ] + ], + "id": "37009106fa07a942" }, { - "cell_type": "markdown", - "id": "4ab96dc2", "metadata": {}, - "source": [ - "### Utils" - ] + "cell_type": "markdown", + "source": "### Utils", + "id": "16d546c2d4b56c7f" }, { - "cell_type": "code", - "execution_count": null, - "id": "35c35a96", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "#| export\n", "@patch\n", @@ -2422,14 +2154,14 @@ " \"Set the lifespan context manager for the FastHTML app\"\n", " if inspect.isasyncgenfunction(value): value = contextlib.asynccontextmanager(value)\n", " self.router.lifespan_context = value" - ] + ], + "id": "7dadb462ba00d11c" }, { - "cell_type": "code", - "execution_count": null, - "id": "3a348474", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "#| export\n", "def serve(\n", @@ -2456,22 +2188,20 @@ " link = f'http://{\"localhost\" if host==\"0.0.0.0\" else host}:{port}'\n", " print('Link: '+ S.light_red.bold(link))\n", " run(f'{appname}:{app}', host=host, port=port, reload=reload, **kwargs)" - ] + ], + "id": "c36b7185c1679ba5" }, { - "cell_type": "markdown", - "id": "428b0e9c", "metadata": {}, - "source": [ - "`procs` runs the app as that many processes on consecutive ports from `port`, each with its own reload supervisor, and defaults to the `PROCS` environment variable. `serve` re-executes the script once per process with `FH_PROCNUM` set to its number, which is also the guard against a child spawning again. An app reads `FH_PROCNUM` for work that only one process should do, such as a background job: it is `'0'` in the first process, and unset in an ordinary single-process run. A reverse proxy in front of the ports decides how requests reach them." - ] + "cell_type": "markdown", + "source": "`procs` runs the app as that many processes on consecutive ports from `port`, each with its own reload supervisor, and defaults to the `PROCS` environment variable. `serve` re-executes the script once per process with `FH_PROCNUM` set to its number, which is also the guard against a child spawning again. An app reads `FH_PROCNUM` for work that only one process should do, such as a background job: it is `'0'` in the first process, and unset in an ordinary single-process run. A reverse proxy in front of the ports decides how requests reach them.", + "id": "b9e62008c275f97b" }, { - "cell_type": "code", - "execution_count": null, - "id": "91b08e9a", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "#| export\n", "def _spawn(n):\n", @@ -2479,22 +2209,20 @@ " ps = [subprocess.Popen([sys.executable, *sys.argv], env={**os.environ, 'FH_PROCNUM':str(i)}) for i in range(n)]\n", " signal.signal(signal.SIGTERM, lambda *a: [p.terminate() for p in ps])\n", " for p in ps: p.wait()" - ] + ], + "id": "e35a3b4cdd465a37" }, { - "cell_type": "markdown", - "id": "1129768b", "metadata": {}, - "source": [ - "Starlette does not cancel a running handler when a client disconnects: the disconnect is only visible as an `http.disconnect` message on the ASGI receive channel, which ordinary handlers never read. `until_disconnect` races a coroutine against that message, cancelling the work if the client goes away first." - ] + "cell_type": "markdown", + "source": "Starlette does not cancel a running handler when a client disconnects: the disconnect is only visible as an `http.disconnect` message on the ASGI receive channel, which ordinary handlers never read. `until_disconnect` races a coroutine against that message, cancelling the work if the client goes away first.", + "id": "24c42a8e514a9e5f" }, { - "cell_type": "code", - "execution_count": null, - "id": "c5220a0e", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "#| export\n", "async def _wait_disconnect(req):\n", @@ -2510,22 +2238,20 @@ " finally:\n", " watch.cancel()\n", " if not work.done(): work.cancel()" - ] + ], + "id": "42ca8bdf84326b3b" }, { - "cell_type": "markdown", - "id": "8c6a8cb8", "metadata": {}, - "source": [ - "`cancel_on_disconnect` applies this to a route handler. `splice_sig` adds a private `Request`-annotated parameter to the exposed signature, which FastHTML fills with the connection, so the handler's own parameters are unchanged. It requires an async handler, since a sync handler runs in a threadpool and cannot be cancelled." - ] + "cell_type": "markdown", + "source": "`cancel_on_disconnect` applies this to a route handler. `splice_sig` adds a private `Request`-annotated parameter to the exposed signature, which FastHTML fills with the connection, so the handler's own parameters are unchanged. It requires an async handler, since a sync handler runs in a threadpool and cannot be cancelled.", + "id": "d6f88d179121010f" }, { - "cell_type": "code", - "execution_count": null, - "id": "c5721d76", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "#| export\n", "def cancel_on_disconnect(\n", @@ -2540,14 +2266,14 @@ " c = until_disconnect(__req, f(**kw))\n", " return await (asyncio.wait_for(c, timeout) if timeout is not None else c)\n", " return splice_sig(_f, f)" - ] + ], + "id": "27f2e4665ebf5bbc" }, { - "cell_type": "code", - "execution_count": null, - "id": "8121968a", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "#| export\n", "class Client:\n", @@ -2561,92 +2287,55 @@ " with from_thread.start_blocking_portal() as portal: return portal.call(_request)\n", "\n", "for o in ('get', 'post', 'delete', 'put', 'patch', 'options'): setattr(Client, o, partialmethod(Client._sync, o))" - ] + ], + "id": "8db5fe95c7d00bec" }, { + "metadata": {}, "cell_type": "code", + "outputs": [], "execution_count": null, - "id": "b163c933", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "'test'" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], "source": [ "app = FastHTML(routes=[Route('/', lambda _: Response('test'))])\n", "cli = Client(app)\n", "\n", "cli.get('/').text" - ] + ], + "id": "ad12879dd1f19e35" }, { - "cell_type": "markdown", - "id": "efc8e6db", "metadata": {}, - "source": [ - "Note that you can also use Starlette's `TestClient` instead of FastHTML's `Client`. They should be largely interchangable." - ] + "cell_type": "markdown", + "source": "Note that you can also use Starlette's `TestClient` instead of FastHTML's `Client`. They should be largely interchangable.", + "id": "a67770455c7eb2b8" }, { - "cell_type": "markdown", - "id": "2d2633dd", "metadata": {}, - "source": [ - "## FastHTML Tests" - ] + "cell_type": "markdown", + "source": "## FastHTML Tests", + "id": "f8a6739566557720" }, { - "cell_type": "code", - "execution_count": null, - "id": "9abc3781", "metadata": {}, + "cell_type": "code", "outputs": [], - "source": [ - "def get_cli(app): return app,TestClient(app),app.route" - ] + "execution_count": null, + "source": "def get_cli(app): return app,TestClient(app),app.route", + "id": "563e9f037bfba8a1" }, { - "cell_type": "code", - "execution_count": null, - "id": "645d8d95", "metadata": {}, + "cell_type": "code", "outputs": [], - "source": [ - "app,cli,rt = get_cli(FastHTML(secret_key='soopersecret'))" - ] + "execution_count": null, + "source": "app,cli,rt = get_cli(FastHTML(secret_key='soopersecret'))", + "id": "541824a436755f55" }, { + "metadata": {}, "cell_type": "code", + "outputs": [], "execution_count": null, - "id": "421262a8", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "[HostRoute(path='/foo', name='foo', methods=['GET', 'HEAD'], host=None)]\n" - ] - }, - { - "data": { - "text/plain": [ - "'/foo?param=value'" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], "source": [ "app,cli,rt = get_cli(FastHTML(title=\"My Custom Title\"))\n", "@app.get\n", @@ -2658,22 +2347,14 @@ "assert 'My Custom Title' in response.text\n", "\n", "foo.to(param='value')" - ] + ], + "id": "c639800adf059ebf" }, { + "metadata": {}, "cell_type": "code", + "outputs": [], "execution_count": null, - "id": "8836b62c", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "[HostRoute(path='/foo', name='foo', methods=['GET', 'HEAD', 'POST'], host='test.foo'), HostRoute(path='/foo', name='foo', methods=['GET', 'HEAD'], host=None)]\n" - ] - } - ], "source": [ "@rt(host='test.foo')\n", "def foo(): return Div(\"Goodbye World\")\n", @@ -2682,38 +2363,27 @@ "\n", "assert \"Goodbye World\" in cli.get('/foo', headers={'host': 'test.foo'}).text\n", "assert \"Hello World\" in cli.get('/foo').text" - ] + ], + "id": "84739e25115b6885" }, { + "metadata": {}, "cell_type": "code", + "outputs": [], "execution_count": null, - "id": "377012de", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "'/foo?param=value'" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], "source": [ "response = cli.get('/foo')\n", "assert 'My Custom Title' in response.text\n", "\n", "foo.to(param='value')" - ] + ], + "id": "a9ab959322b3c533" }, { - "cell_type": "code", - "execution_count": null, - "id": "2ebd6270", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "app,cli,rt = get_cli(FastHTML())\n", "\n", @@ -2722,26 +2392,26 @@ "\n", "txt = cli.get('/xt2').text\n", "assert 'FastHTML page' in txt and '

bar

' in txt and '' in txt" - ] + ], + "id": "4b7beef96901eff5" }, { - "cell_type": "code", - "execution_count": null, - "id": "274653c2", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "def test_r(cli, path, exp, meth='get', hx=False, **kwargs):\n", " if hx: kwargs['headers'] = {'hx-request':\"1\"}\n", " test_eq(getattr(cli, meth)(path, **kwargs).text, exp)" - ] + ], + "id": "772f8f233bfdf3a0" }, { - "cell_type": "code", - "execution_count": null, - "id": "b8a77cde", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "@dataclass\n", "class Card: id:str; title:str\n", @@ -2756,14 +2426,14 @@ "test_r(cli, '/class-cards/abc', '{\"id\":\"abc\",\"title\":\"Foo\"}', 'patch', data={'title':'Foo'})\n", "test_eq(cli.delete('/class-cards/abc').text, 'delete abc')\n", "test_eq(CardMethods.to(id='xyz'), '/class-cards/xyz')" - ] + ], + "id": "a3cba3e1f15e799a" }, { - "cell_type": "code", - "execution_count": null, - "id": "ac7b527d", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "@rt\n", "class Things:\n", @@ -2771,95 +2441,54 @@ "\n", "test_eq(cli.get('/things?id=7').text, 'thing 7')\n", "test_eq(Things.to(id=7), '/things?id=7')" - ] + ], + "id": "97b51681c70ff08" }, { + "metadata": {}, "cell_type": "code", + "outputs": [], "execution_count": null, - "id": "8a6ed879", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "'Hi there'" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], "source": [ "@rt(\"/hi\")\n", "def get(): return 'Hi there'\n", "\n", "r = cli.get('/hi')\n", "r.text" - ] + ], + "id": "b0d1876823809add" }, { + "metadata": {}, "cell_type": "code", + "outputs": [], "execution_count": null, - "id": "a8e723fc", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "'Postal'" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], "source": [ "@rt(\"/hi\")\n", "def post(): return 'Postal'\n", "\n", "cli.post('/hi').text" - ] + ], + "id": "afc2ab1803fa418a" }, { + "metadata": {}, "cell_type": "code", + "outputs": [], "execution_count": null, - "id": "274666db", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "'testserver'" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], "source": [ "@app.get(\"/hostie\")\n", "def show_host(req): return req.headers['host']\n", "\n", "cli.get('/hostie').text" - ] + ], + "id": "a475f9d4844d8a3f" }, { + "metadata": {}, "cell_type": "code", + "outputs": [], "execution_count": null, - "id": "72428702", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Message text was: Hi! with session bar, from client: Address(host='testclient', port=50000)\n" - ] - } - ], "source": [ "@app.get(\"/setsess\")\n", "def set_sess(session):\n", @@ -2875,215 +2504,100 @@ " data = ws.receive_text()\n", "assert 'Message text was: Hi! with session bar' in data\n", "print(data)" - ] + ], + "id": "3177015fbac381ec" }, { + "metadata": {}, "cell_type": "code", + "outputs": [], "execution_count": null, - "id": "36292bf3", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "'a yoyo'" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], "source": [ "@rt\n", "def yoyo(): return 'a yoyo'\n", "\n", "cli.post('/yoyo').text" - ] + ], + "id": "6b0d7ef1d4bd445d" }, { + "metadata": {}, "cell_type": "code", + "outputs": [], "execution_count": null, - "id": "0d813cd0", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "\n", - "\n", - "
Text.
\n", - "\n" - ] - }, - { - "name": "stdout", - "output_type": "stream", - "text": [ - "\n" - ] - } - ], "source": [ "@app.get\n", "def autopost(): return Html(Div('Text.', hx_post=yoyo()))\n", "print(cli.get('/autopost').text)" - ] + ], + "id": "7c411a85a21ad08e" }, { + "metadata": {}, "cell_type": "code", + "outputs": [], "execution_count": null, - "id": "52dde0da", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "\n", - "\n", - " \n", - "
Text.
\n", - " \n", - "\n" - ] - }, - { - "name": "stdout", - "output_type": "stream", - "text": [ - "\n" - ] - } - ], "source": [ "@app.get\n", "def autopost2(): return Html(Body(Div('Text.', cls='px-2', hx_post=show_host.to(a='b'))))\n", "print(cli.get('/autopost2').text)" - ] + ], + "id": "8c38b939291ab644" }, { + "metadata": {}, "cell_type": "code", + "outputs": [], "execution_count": null, - "id": "d84d98f1", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "\n", - "\n", - "
Text.
\n", - "\n" - ] - }, - { - "name": "stdout", - "output_type": "stream", - "text": [ - "\n" - ] - } - ], "source": [ "@app.get\n", "def autoget2(): return Html(Div('Text.', hx_get=show_host))\n", "print(cli.get('/autoget2').text)" - ] + ], + "id": "a77a1f47c56e36d9" }, { + "metadata": {}, "cell_type": "code", + "outputs": [], "execution_count": null, - "id": "64343367", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "'Good day to you, Alexis!'" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], "source": [ "@rt('/user/{nm}', name='gday')\n", "def get(nm:str=''): return f\"Good day to you, {nm}!\"\n", "cli.get('/user/Alexis').text" - ] + ], + "id": "3c20651b84de0f59" }, { + "metadata": {}, "cell_type": "code", + "outputs": [], "execution_count": null, - "id": "29a96715", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "\n", - "\n", - "
Text.
\n", - "\n" - ] - }, - { - "name": "stdout", - "output_type": "stream", - "text": [ - "\n" - ] - } - ], "source": [ "@app.get\n", "def autolink(): return Html(Div('Text.', link=uri('gday', nm='Alexis')))\n", "print(cli.get('/autolink').text)" - ] + ], + "id": "2c788900a2ccdb73" }, { + "metadata": {}, "cell_type": "code", + "outputs": [], "execution_count": null, - "id": "54266599", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "'http://testserver/user/Alexis; http://testserver/hostie'" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], "source": [ "@rt('/link')\n", "def get(req): return f\"{req.url_for('gday', nm='Alexis')}; {req.url_for('show_host')}\"\n", "\n", "cli.get('/link').text" - ] + ], + "id": "f657a1f73d5dfd2f" }, { + "metadata": {}, "cell_type": "code", + "outputs": [], "execution_count": null, - "id": "162b811e", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Background task completed!\n" - ] - } - ], "source": [ "@app.get(\"/background\")\n", "async def background_task(request):\n", @@ -3093,24 +2607,22 @@ " return P(\"Task started\"), BackgroundTask(long_running_task)\n", "\n", "response = cli.get(\"/background\")" - ] + ], + "id": "8635c1055169bedf" }, { - "cell_type": "code", - "execution_count": null, - "id": "db0281cf", "metadata": {}, + "cell_type": "code", "outputs": [], - "source": [ - "test_eq(app.router.url_path_for('gday', nm='Jeremy'), '/user/Jeremy')" - ] + "execution_count": null, + "source": "test_eq(app.router.url_path_for('gday', nm='Jeremy'), '/user/Jeremy')", + "id": "b01c37683cd5749d" }, { - "cell_type": "code", - "execution_count": null, - "id": "b827960a", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "hxhdr = {'headers':{'hx-request':\"1\"}}\n", "\n", @@ -3133,62 +2645,62 @@ "\n", "txt = cli.get('/xt3').text\n", "assert 'FastHTML page' not in txt and 'hi' in txt and '

there

' in txt" - ] + ], + "id": "985d18d4a0b94a29" }, { - "cell_type": "code", - "execution_count": null, - "id": "1c2311f8", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "# declaration-time warnings\n", "def _noanno(nope): return nope\n", "def _bare(names:list): return str(names)\n", "test_warns(lambda: rt('/oops')(_noanno))\n", "test_warns(lambda: rt('/barelist')(_bare))" - ] + ], + "id": "2ce18b792ac77487" }, { - "cell_type": "code", - "execution_count": null, - "id": "381a1b68", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "# runtime warnings\n", "test_warns(lambda: cli.get('/oops?nope=1'))\n", "test_warns(lambda: cli.get('/barelist?names=1'))" - ] + ], + "id": "26ea68a93689fd0b" }, { - "cell_type": "code", - "execution_count": null, - "id": "80238019", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "ModelName = str_enum('ModelName', \"alexnet\", \"resnet\", \"lenet\")\n", "fake_db = [{\"name\": \"Foo\"}, {\"name\": \"Bar\"}]" - ] + ], + "id": "e94e2e251db62443" }, { - "cell_type": "code", - "execution_count": null, - "id": "1b4b5717", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "@rt('/html/{idx}')\n", "async def get(idx:int): return Body(H4(f'Next is {idx+1}.'))" - ] + ], + "id": "32fa349b79d75e70" }, { - "cell_type": "code", - "execution_count": null, - "id": "dd017867", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "@rt(\"/models/{nm}\")\n", "def get(nm:ModelName): return nm\n", @@ -3207,14 +2719,14 @@ "\n", "@rt(\"/unionidxl/\")\n", "def get(idx:list[int] | None): return str(idx)" - ] + ], + "id": "a4b214dffb848f61" }, { - "cell_type": "code", - "execution_count": null, - "id": "52d9a3f2", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "r = cli.get('/html/1', headers={'hx-request':\"1\"})\n", "assert '

Next is 2.

' in r.text\n", @@ -3228,25 +2740,14 @@ "assert cli.get('/idxl/?idx=1&idx=g').status_code == 404\n", "test_r(cli, '/optidxl/?idx=1&idx=2', '[1, 2]')\n", "test_r(cli, '/unionidxl/?idx=1&idx=2', '[1, 2]')" - ] + ], + "id": "5496149d1a02c20d" }, { + "metadata": {}, "cell_type": "code", + "outputs": [], "execution_count": null, - "id": "bb8154cc", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "'got sub/a.b'" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], "source": [ "app = FastHTML()\n", "rt = app.route\n", @@ -3256,45 +2757,30 @@ "@app.route(r'/static/{path:path}')\n", "def foo(path:str, a:int): return f'also got {path},{a}'\n", "cli.get('/static/sub/a.b.jpg').text" - ] + ], + "id": "855956c3bfb4adee" }, { + "metadata": {}, "cell_type": "code", + "outputs": [], "execution_count": null, - "id": "65a29643", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "'also got sub/a.b,1'" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "cli.get('/static/sub/a.b?a=1').text" - ] + "source": "cli.get('/static/sub/a.b?a=1').text", + "id": "97b1292db472196b" }, { - "cell_type": "code", - "execution_count": null, - "id": "6bc9564c", "metadata": {}, + "cell_type": "code", "outputs": [], - "source": [ - "app.chk = 'foo'" - ] + "execution_count": null, + "source": "app.chk = 'foo'", + "id": "ea361055b7188aff" }, { - "cell_type": "code", - "execution_count": null, - "id": "b8be4ef3", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "@app.get(\"/booly/\")\n", "def _(coming:bool=True): return 'Coming' if coming else 'Not coming'\n", @@ -3322,14 +2808,14 @@ "\n", "@app.get(\"/app4\")\n", "def _(foo:FastHTML): return Redirect(\"http://example.org\")" - ] + ], + "id": "7f15062539128c48" }, { - "cell_type": "code", - "execution_count": null, - "id": "5f045cf9", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "test_r(cli, '/booly/?coming=true', 'Coming')\n", "test_r(cli, '/booly/?coming=no', 'Not coming')\n", @@ -3339,59 +2825,59 @@ "test_r(cli, '/hxtest' , '1', headers={'HX-Request':'1'})\n", "test_r(cli, '/hxtest2', '1', headers={'HX-Request':'1'})\n", "test_r(cli, '/app' , 'foo')" - ] + ], + "id": "944594c4209fdc7c" }, { - "cell_type": "code", - "execution_count": null, - "id": "52f9f934", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "r = cli.get('/app2', **hxhdr)\n", "test_eq(r.text, 'foo')\n", "test_eq(r.headers['mykey'], 'myval')" - ] + ], + "id": "b4689d6ff7d4123a" }, { - "cell_type": "code", - "execution_count": null, - "id": "26d316b6", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "r = cli.get('/app3')\n", "test_eq(r.headers['HX-Location'], 'http://example.org')" - ] + ], + "id": "295ae52452b974b6" }, { - "cell_type": "code", - "execution_count": null, - "id": "704aeba6", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "r = cli.get('/app4', follow_redirects=False)\n", "test_eq(r.status_code, 303)" - ] + ], + "id": "5dfa9fdf9be7c0ab" }, { - "cell_type": "code", - "execution_count": null, - "id": "5fa127d5", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "r = cli.get('/app4', headers={'HX-Request':'1'})\n", "test_eq(r.headers['HX-Redirect'], 'http://example.org')" - ] + ], + "id": "c25ee2b4ae9af9db" }, { - "cell_type": "code", - "execution_count": null, - "id": "356db6c0", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "@rt\n", "def meta(): return ((Title('hi'), H1('hi')), (Meta(property='image'), Meta(property='site_name')))\n", @@ -3399,14 +2885,14 @@ "t = cli.post('/meta').text\n", "assert re.search(r'\\s*

hi

\\s*', t)\n", "assert 'It worked!\" in response and \"

15, Lorem

\" in response" - ] + ], + "id": "f8c5a79a9e268cad" }, { - "cell_type": "code", - "execution_count": null, - "id": "0aeaac36", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "# Testing POST with Content-Type: application/json\n", "@app.post(\"/bodytext\")\n", @@ -3529,39 +3013,22 @@ "\n", "response = cli.post('/bodytext', headers={\"Content-Type\": \"application/json\"}, data=s).text\n", "test_eq(response, '{\"b\": \"Lorem\", \"a\": 15}')" - ] + ], + "id": "1c271ec1f072e066" }, { - "cell_type": "code", - "execution_count": null, - "id": "4034ee37", "metadata": {}, + "cell_type": "code", "outputs": [], - "source": [ - "files = [('files', ('file1.txt', b'content1')), ('files', ('file2.txt', b'content2'))]" - ] + "execution_count": null, + "source": "files = [('files', ('file1.txt', b'content1')), ('files', ('file2.txt', b'content2'))]", + "id": "93a69784d0a2b6b3" }, { + "metadata": {}, "cell_type": "code", + "outputs": [], "execution_count": null, - "id": "04881594", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "200\n" - ] - }, - { - "name": "stdout", - "output_type": "stream", - "text": [ - "content1,content2\n" - ] - } - ], "source": [ "@rt(\"/uploads\")\n", "async def post(files:list[UploadFile]): return ','.join([(await file.read()).decode() for file in files])\n", @@ -3569,44 +3036,26 @@ "res = cli.post('/uploads', files=files)\n", "print(res.status_code)\n", "print(res.text)" - ] + ], + "id": "8f88c027dbebba62" }, { - "cell_type": "code", - "execution_count": null, - "id": "28a99667", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "res = cli.post('/uploads', files=[files[0]])\n", "test_eq(res.status_code, 200)\n", "test_eq(res.text, 'content1')" - ] + ], + "id": "a1705546441529ca" }, { + "metadata": {}, "cell_type": "code", + "outputs": [], "execution_count": null, - "id": "5bce33f0", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Set to 2026-06-29 21:09:52.332526\n" - ] - }, - { - "data": { - "text/plain": [ - "'Session time: 2026-06-29 21:09:52.332526'" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], "source": [ "@rt(\"/setsess\")\n", "def get(sess, foo:str=''):\n", @@ -3621,14 +3070,14 @@ "time.sleep(0.01)\n", "\n", "cli.get('/getsess').text" - ] + ], + "id": "ad0e269042b27e7e" }, { - "cell_type": "code", - "execution_count": null, - "id": "249fce31", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "@rt(\"/sess-first\")\n", "def post(sess, name: str):\n", @@ -3641,69 +3090,59 @@ "def get(sess): return sess['name']\n", "\n", "test_eq(cli.get('/getsess-all').text, '2')" - ] + ], + "id": "f5ca9e1ef115a62a" }, { + "metadata": {}, "cell_type": "code", + "outputs": [], "execution_count": null, - "id": "4d17ab9c", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "# Release notes\n" - ] - } - ], "source": [ "@rt(\"/upload\")\n", "async def post(uf:UploadFile): return (await uf.read()).decode()\n", "\n", "with open('../../CHANGELOG.md', 'rb') as f: print(cli.post('/upload', files={'uf':f}, data={'msg':'Hello'}).text[:15])" - ] + ], + "id": "409b7720eb224b52" }, { - "cell_type": "code", - "execution_count": null, - "id": "102c17ab", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "@rt(\"/form-submit/{list_id}\")\n", "def options(list_id: str):\n", " headers = {'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'POST', 'Access-Control-Allow-Headers': '*'}\n", " return Response(status_code=200, headers=headers)" - ] + ], + "id": "f343fe095bb6667" }, { - "cell_type": "code", - "execution_count": null, - "id": "85bf2984", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "h = cli.options('/form-submit/2').headers\n", "test_eq(h['Access-Control-Allow-Methods'], 'POST')" - ] + ], + "id": "c079a9480076de20" }, { - "cell_type": "code", - "execution_count": null, - "id": "e4fc13b0", "metadata": {}, + "cell_type": "code", "outputs": [], - "source": [ - "from fasthtml.authmw import user_pwd_auth" - ] + "execution_count": null, + "source": "from fasthtml.authmw import user_pwd_auth", + "id": "c3a0b4e98373614e" }, { - "cell_type": "code", - "execution_count": null, - "id": "1f11eab1", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "def _not_found(req, exc): return Div('nope')\n", "\n", @@ -3712,14 +3151,14 @@ "txt = cli.get('/').text\n", "assert '
nope
' in txt\n", "assert '' in txt" - ] + ], + "id": "2f8b30794712e0c2" }, { - "cell_type": "code", - "execution_count": null, - "id": "063b7f43", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "app,cli,rt = get_cli(FastHTML())\n", "\n", @@ -3728,14 +3167,14 @@ "\n", "assert 'Hello Uma, age 5' in cli.get('/uma/5').text\n", "assert '404 Not Found' in cli.get('/uma/five').text" - ] + ], + "id": "90ba5b8403a3879d" }, { - "cell_type": "code", - "execution_count": null, - "id": "efd6fc6c", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "auth = user_pwd_auth(testuser='spycraft')\n", "app,cli,rt = get_cli(FastHTML(middleware=[auth]))\n", @@ -3745,14 +3184,14 @@ "\n", "test_eq(cli.get('/locked').text, 'not authenticated')\n", "test_eq(cli.get('/locked', auth=(\"testuser\",\"spycraft\")).text, 'Hello, testuser')" - ] + ], + "id": "cd1418adab7bc3b1" }, { - "cell_type": "code", - "execution_count": null, - "id": "32520197", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "auth = user_pwd_auth(testuser='spycraft')\n", "app,cli,rt = get_cli(FastHTML(middleware=[auth]))\n", @@ -3762,32 +3201,28 @@ "\n", "test_eq(cli.get('/locked').text, 'not authenticated')\n", "test_eq(cli.get('/locked', auth=(\"testuser\",\"spycraft\")).text, 'Hello, testuser')" - ] + ], + "id": "3d6b883e14f63a74" }, { - "cell_type": "markdown", - "id": "967001f3", "metadata": {}, - "source": [ - "Check that afterware like toasts are called correctly." - ] + "cell_type": "markdown", + "source": "Check that afterware like toasts are called correctly.", + "id": "504abfeb5c1f9a9c" }, { - "cell_type": "code", - "execution_count": null, - "id": "09a5fb96", "metadata": {}, + "cell_type": "code", "outputs": [], - "source": [ - "from fasthtml.toaster import *" - ] + "execution_count": null, + "source": "from fasthtml.toaster import *", + "id": "bf8618699f50aed1" }, { - "cell_type": "code", - "execution_count": null, - "id": "c7500555", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "app,cli,rt = get_cli(FastHTML())\n", "\n", @@ -3822,32 +3257,28 @@ "\n", "r = cli.get('/')\n", "assert tm in r.text" - ] + ], + "id": "8d549d9a5c93d99d" }, { - "cell_type": "markdown", - "id": "bd0e4c06", "metadata": {}, - "source": [ - "Here's a quick sanity check to confirm that toasts are rendered in the toast container correctly. See [issue](https://github.com/AnswerDotAI/fasthtml/issues/762)." - ] + "cell_type": "markdown", + "source": "Here's a quick sanity check to confirm that toasts are rendered in the toast container correctly. See [issue](https://github.com/AnswerDotAI/fasthtml/issues/762).", + "id": "9fab408e2e6e686" }, { - "cell_type": "code", - "execution_count": null, - "id": "e2417e5f", "metadata": {}, + "cell_type": "code", "outputs": [], - "source": [ - "assert 'id=\"fh-toast-container\"' in r.text" - ] + "execution_count": null, + "source": "assert 'id=\"fh-toast-container\"' in r.text", + "id": "4bd5e983e3d3af53" }, { - "cell_type": "code", - "execution_count": null, - "id": "f95e80d7", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "app,cli,rt = get_cli(FastHTML(on_startup=[lambda: setattr(app, '_started', True)],\n", " on_shutdown=[lambda: setattr(app, '_stopped', True)]))\n", @@ -3857,14 +3288,14 @@ "\n", "with cli: test_eq(cli.get('/').text, 'True')\n", "test_eq(app._stopped, True)" - ] + ], + "id": "f5bd3ba8f7e070c1" }, { - "cell_type": "code", - "execution_count": null, - "id": "190ce9d0", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "app,cli,rt = get_cli(FastHTML())\n", "\n", @@ -3875,22 +3306,20 @@ "def index(): return app._evt\n", "\n", "with cli: test_eq(cli.get('/').text, 'fired')" - ] + ], + "id": "e1e0a2981bdd9bed" }, { - "cell_type": "markdown", - "id": "b9fdbdd8", "metadata": {}, - "source": [ - "A route-level `before` can set session data, short-circuit with a response, or raise to block access:" - ] + "cell_type": "markdown", + "source": "A route-level `before` can set session data, short-circuit with a response, or raise to block access:", + "id": "e186cdcbef7aa053" }, { - "cell_type": "code", - "execution_count": null, - "id": "f94ea388", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "def check_user(sess, user:str=''):\n", " if user == 'admin':\n", @@ -3905,22 +3334,20 @@ "test_eq(cli.get('/dashboard?user=admin').text, 'bar')\n", "test_eq(cli.get('/dashboard?user=guest').text, 'guest view')\n", "test_eq(cli.get('/dashboard?user=other').status_code, 403)" - ] + ], + "id": "375bfb6e0574c3b1" }, { - "cell_type": "markdown", - "id": "35615416", "metadata": {}, - "source": [ - "Multiple `before` functions run in order, each receiving the injected request params:" - ] + "cell_type": "markdown", + "source": "Multiple `before` functions run in order, each receiving the injected request params:", + "id": "59fd36c5878e8631" }, { - "cell_type": "code", - "execution_count": null, - "id": "6b751acb", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "def set_a(sess): sess['a'] = 1\n", "def set_b(sess): sess['b'] = 2\n", @@ -3929,22 +3356,20 @@ "def get(sess): return f\"{sess.get('a')},{sess.get('b')}\"\n", "\n", "test_eq(cli.get('/multi').text, '1,2')" - ] + ], + "id": "1b6335c5da6b5da4" }, { - "cell_type": "markdown", - "id": "49cc8791", "metadata": {}, - "source": [ - "A truthy return from any `before` becomes the response; remaining `before`s and the handler are skipped (return `None` to continue):" - ] + "cell_type": "markdown", + "source": "A truthy return from any `before` becomes the response; remaining `before`s and the handler are skipped (return `None` to continue):", + "id": "b8218676a7553fae" }, { - "cell_type": "code", - "execution_count": null, - "id": "83188ab0", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "calls = []\n", "def first(sess): \n", @@ -3957,22 +3382,20 @@ "\n", "test_eq(cli.get('/chain').text, 'stop')\n", "test_eq(calls, ['first'])" - ] + ], + "id": "ff2355f5ac88a72d" }, { - "cell_type": "markdown", - "id": "a43466d4", "metadata": {}, - "source": [ - "`cancel_on_disconnect` handlers keep their normal parameters; the handler is cancelled if the client disconnects, or after `timeout` seconds if given:" - ] + "cell_type": "markdown", + "source": "`cancel_on_disconnect` handlers keep their normal parameters; the handler is cancelled if the client disconnects, or after `timeout` seconds if given:", + "id": "80260448c4476ee0" }, { - "cell_type": "code", - "execution_count": null, - "id": "4457e14e", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "app,cli,rt = get_cli(FastHTML())\n", "\n", @@ -3981,14 +3404,14 @@ "async def cq(q:str): return f'got {q}'\n", "\n", "test_eq(cli.get('/cq?q=x').text, 'got x')" - ] + ], + "id": "b2148b69758de6f" }, { - "cell_type": "code", - "execution_count": null, - "id": "59ed14fc", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "@rt('/sleepy')\n", "@cancel_on_disconnect(timeout=0.01)\n", @@ -3997,22 +3420,20 @@ " return 'nope'\n", "\n", "test_fail(lambda: cli.get('/sleepy'))" - ] + ], + "id": "ac7273a868548b84" }, { - "cell_type": "markdown", - "id": "c03768de", "metadata": {}, - "source": [ - "On disconnect the handler is cancelled and an empty response returned, which the server discards since the client is gone. Here we simulate the ASGI `http.disconnect` message directly:" - ] + "cell_type": "markdown", + "source": "On disconnect the handler is cancelled and an empty response returned, which the server discards since the client is gone. Here we simulate the ASGI `http.disconnect` message directly:", + "id": "5819b50f4728bc55" }, { - "cell_type": "code", - "execution_count": null, - "id": "8e78bea6", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "async def _disc(): return {'type': 'http.disconnect'}\n", "cancelled = []\n", @@ -4030,22 +3451,20 @@ "\n", "test_eq(run_sync(_t()).status_code, 204)\n", "test_eq(cancelled, [True])" - ] + ], + "id": "6dd453e187a01b13" }, { - "cell_type": "markdown", - "id": "6a014add", "metadata": {}, - "source": [ - "## APIRouter" - ] + "cell_type": "markdown", + "source": "## APIRouter", + "id": "cb43430858dcac10" }, { - "cell_type": "code", - "execution_count": null, - "id": "d5223a9a", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "#| export\n", "class RouteFuncs:\n", @@ -4057,14 +3476,14 @@ " try: return self._funcs[name]\n", " except KeyError: raise AttributeError(f\"No route named {name} found in route functions\")\n", " def __dir__(self): return list(self._funcs.keys())" - ] + ], + "id": "6d212239ee4b3ebb" }, { - "cell_type": "code", - "execution_count": null, - "id": "0f08cb5e", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "#| export\n", "class APIRouter:\n", @@ -4105,24 +3524,22 @@ " \"Add a websocket route at `path`\"\n", " def f(func=noop): return self.wss.append((func, f\"{self.prefix}{path}\", conn, disconn, name, middleware))\n", " return f" - ] + ], + "id": "c069560553ea4e31" }, { - "cell_type": "code", - "execution_count": null, - "id": "22e17ec8", "metadata": {}, + "cell_type": "code", "outputs": [], - "source": [ - "ar = APIRouter()" - ] + "execution_count": null, + "source": "ar = APIRouter()", + "id": "7053f84ef1ee93f6" }, { - "cell_type": "code", - "execution_count": null, - "id": "61030ee4", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "@ar(\"/hi\")\n", "def get(): return 'Hi there'\n", @@ -4145,25 +3562,25 @@ "\n", "@ar.ws(\"/ws\")\n", "def ws(self, msg:str): return f\"Message text was: {msg}\"" - ] + ], + "id": "c0ff4dc1dfe83148" }, { - "cell_type": "code", - "execution_count": null, - "id": "cd413b0d", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "app,cli,_ = get_cli(FastHTML())\n", "ar.to_app(app)" - ] + ], + "id": "d78e389d3610d965" }, { - "cell_type": "code", - "execution_count": null, - "id": "8c265ff8", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "assert str(yoyo) == '/yoyo'\n", "# ensure route functions are properly discoverable on `APIRouter` and `APIRouter.rt_funcs`\n", @@ -4174,14 +3591,14 @@ "with ExceptionExpected(): ar.rt_funcs.blah()\n", "# ensure any route functions named using an HTTPMethod are not discoverable via `rt_funcs`\n", "assert \"get\" not in ar.rt_funcs._funcs.keys()" - ] + ], + "id": "c8ebe7cfdc63718" }, { - "cell_type": "code", - "execution_count": null, - "id": "8f7c5710", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "test_eq(cli.get('/hi').text, 'Hi there')\n", "test_eq(cli.post('/hi').text, 'Postal')\n", @@ -4195,37 +3612,35 @@ "test_r(cli, '/class-cards/abc', '{\"id\":\"abc\",\"title\":\"Foo\"}', 'patch', data={'title':'Foo'})\n", "test_eq(cli.delete('/class-cards/abc').text, 'delete abc')\n", "test_eq(CardMethods.to(id='xyz'), '/class-cards/xyz')" - ] + ], + "id": "6a60b59b118846a6" }, { - "cell_type": "code", - "execution_count": null, - "id": "1236de78", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "with cli.websocket_connect('/ws') as ws:\n", " ws.send_text('{\"msg\":\"Hi!\"}')\n", " data = ws.receive_text()\n", " assert data == 'Message text was: Hi!'" - ] + ], + "id": "b8e12162ea3e310c" }, { - "cell_type": "code", - "execution_count": null, - "id": "02a4e649", "metadata": {}, + "cell_type": "code", "outputs": [], - "source": [ - "ar2 = APIRouter(\"/products\")" - ] + "execution_count": null, + "source": "ar2 = APIRouter(\"/products\")", + "id": "34dc5eb7b3152b1c" }, { - "cell_type": "code", - "execution_count": null, - "id": "151b9e3c", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "@ar2(\"/hi\")\n", "def get(): return 'Hi there'\n", @@ -4246,25 +3661,25 @@ "\n", "@ar2.ws(\"/ws\")\n", "def ws(self, msg:str): return f\"Message text was: {msg}\"" - ] + ], + "id": "5ea40de23ef540fd" }, { - "cell_type": "code", - "execution_count": null, - "id": "77ce8548", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "app,cli,_ = get_cli(FastHTML())\n", "ar2.to_app(app)" - ] + ], + "id": "50efe1782d71c63d" }, { - "cell_type": "code", - "execution_count": null, - "id": "f1fc8425", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "assert str(yoyo) == '/products/yoyo'\n", "assert ar2.prefix == '/products'\n", @@ -4274,14 +3689,14 @@ "with ExceptionExpected(): ar2.blah()\n", "with ExceptionExpected(): ar2.rt_funcs.blah()\n", "assert \"get\" not in ar2.rt_funcs._funcs.keys()" - ] + ], + "id": "5e76acbce9b744e9" }, { - "cell_type": "code", - "execution_count": null, - "id": "f265860d", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "test_eq(cli.get('/products/hi').text, 'Hi there')\n", "test_eq(cli.post('/products/hi').text, 'Postal')\n", @@ -4293,38 +3708,38 @@ "\n", "test_eq(cli.get('/products/products?id=7').text, 'product 7')\n", "test_eq(Products.to(id=7), '/products/products?id=7')" - ] + ], + "id": "74d0e896f59faa34" }, { - "cell_type": "code", - "execution_count": null, - "id": "e38d99cf", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "with cli.websocket_connect('/products/ws') as ws:\n", " ws.send_text('{\"msg\":\"Hi!\"}')\n", " data = ws.receive_text()\n", " assert data == 'Message text was: Hi!'" - ] + ], + "id": "3f575fb7222c54cd" }, { - "cell_type": "code", - "execution_count": null, - "id": "259a0f53", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "#| export\n", "for o in all_meths: setattr(APIRouter, o, partialmethod(APIRouter.__call__, methods=o))" - ] + ], + "id": "6d6695412ac8dccd" }, { - "cell_type": "code", - "execution_count": null, - "id": "f61d110c", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "@ar.get\n", "def hi2(): return 'Hi there'\n", @@ -4339,32 +3754,28 @@ "def _(): return 'Hi there'\n", "@ar2.post(\"/post2\")\n", "def _(): return 'Postal'" - ] + ], + "id": "2fd1f4a196f51927" }, { - "cell_type": "markdown", - "id": "dfa6f859", "metadata": {}, - "source": [ - "## Extras" - ] + "cell_type": "markdown", + "source": "## Extras", + "id": "d14d79e176792cd8" }, { - "cell_type": "code", - "execution_count": null, - "id": "7438435e", "metadata": {}, + "cell_type": "code", "outputs": [], - "source": [ - "app,cli,rt = get_cli(FastHTML(secret_key='soopersecret'))" - ] + "execution_count": null, + "source": "app,cli,rt = get_cli(FastHTML(secret_key='soopersecret'))", + "id": "710d59fe07e76a4e" }, { - "cell_type": "code", - "execution_count": null, - "id": "e518de83", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "#| export\n", "def cookie(key: str, value=\"\", max_age=None, expires=None, path=\"/\", domain=None, secure=False, httponly=False, samesite=\"lax\",):\n", @@ -4382,48 +3793,14 @@ " cookie[key][\"samesite\"] = samesite\n", " cookie_val = cookie.output(header=\"\").strip()\n", " return HttpHeader(\"set-cookie\", cookie_val)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "919e600a", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "\n", - "\n", - " \n", - " FastHTML page\n", - " \n", - " \n", - " \n", - " \n", - " \n", - "\n" - ] - }, - { - "name": "stdout", - "output_type": "stream", - "text": [ - "\n" - ] - }, - { - "data": { - "text/plain": [ - "'Cookie was set at time 21:09:55.336114'" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } ], + "id": "4b8cabb822ba5c06" + }, + { + "metadata": {}, + "cell_type": "code", + "outputs": [], + "execution_count": null, "source": [ "@rt(\"/setcookie\")\n", "def get(req): return cookie('now', datetime.now())\n", @@ -4434,28 +3811,28 @@ "print(cli.get('/setcookie').text)\n", "time.sleep(0.01)\n", "cli.get('/getcookie').text" - ] + ], + "id": "9020523bd7e93f" }, { - "cell_type": "code", - "execution_count": null, - "id": "8816f277", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "#| export\n", "def reg_re_param(m, s):\n", " \"Register a Starlette URL convertor named `m` matching regex `s`\"\n", " cls = get_class(f'{m}Conv', sup=StringConvertor, regex=s)\n", " register_url_convertor(m, cls())" - ] + ], + "id": "5cdac562bf659976" }, { - "cell_type": "code", - "execution_count": null, - "id": "e9535978", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "#| export\n", "# Starlette doesn't have the '?', so it chomps the whole remaining URL\n", @@ -4468,14 +3845,14 @@ " \"Add a static route at URL path `prefix` with files from `static_path` and `exts` defined by `reg_re_param()`\"\n", " @self.get(f\"{prefix}{{fname:path}}.{{ext:{exts}}}\")\n", " async def get(fname:str, ext:str): return FileResponse(f'{static_path}/{fname}.{ext}')" - ] + ], + "id": "f39ce8a9974eb311" }, { - "cell_type": "code", - "execution_count": null, - "id": "9a70842e", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "reg_re_param(\"imgext\", \"ico|gif|jpg|jpeg|webm|pdf\")\n", "\n", @@ -4483,25 +3860,25 @@ "def get(fn:str, path:str, ext:str): return f\"Getting {fn}.{ext} from /{path}\"\n", "\n", "test_r(cli, '/static/foo/jph.me.ico', 'Getting jph.me.ico from /foo/')" - ] + ], + "id": "652c879213bfb742" }, { - "cell_type": "code", - "execution_count": null, - "id": "8bb51383", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "app.static_route_exts()\n", "assert 'These are the source notebooks for FastHTML' in cli.get('/README.txt').text" - ] + ], + "id": "14ac1dcb187e9ded" }, { - "cell_type": "code", - "execution_count": null, - "id": "b31de65a", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "#| export\n", "@patch\n", @@ -4509,25 +3886,25 @@ " \"Add a static route at URL path `prefix` with files from `static_path` and single `ext` (including the '.')\"\n", " @self.get(f\"{prefix}{{fname:path}}{ext}\")\n", " async def get(fname:str): return FileResponse(f'{static_path}/{fname}{ext}')" - ] + ], + "id": "f3b305241d618c09" }, { - "cell_type": "code", - "execution_count": null, - "id": "d4ff5919", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "app.static_route('.md', static_path='../..')\n", "assert 'THIS FILE WAS AUTOGENERATED' in cli.get('/README.md').text" - ] + ], + "id": "a71a0eb39efe8d5c" }, { - "cell_type": "code", - "execution_count": null, - "id": "f63b7a03", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "#| export\n", "class StaticNoCache(StaticFiles):\n", @@ -4536,14 +3913,14 @@ " resp = super().file_response(*args, **kwargs)\n", " resp.headers.setdefault(\"Cache-Control\", \"no-cache\")\n", " return resp" - ] + ], + "id": "dfc415e286f4b8" }, { - "cell_type": "code", - "execution_count": null, - "id": "74801f94", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "#| export\n", "class StaticImmutable(StaticFiles):\n", @@ -4552,22 +3929,20 @@ " resp = super().file_response(*args, **kwargs)\n", " resp.headers.setdefault(\"Cache-Control\", \"public, max-age=31536000, immutable\")\n", " return resp" - ] + ], + "id": "23fae82950b80317" }, { - "cell_type": "markdown", - "id": "1c0531b8", "metadata": {}, - "source": [ - "These two classes are the poles of static-file caching. `StaticNoCache` makes the browser revalidate on every use: always fresh at the cost of a conditional request each time, right for files that change under a stable URL (and for dev, where you want edits visible on reload). `StaticImmutable` promises the URL's content will never change, so the browser may cache it forever with no requests at all: only safe when a changed file gets a changed URL, which is what `vurl` or a bundler's content-hashed filenames provide." - ] + "cell_type": "markdown", + "source": "These two classes are the poles of static-file caching. `StaticNoCache` makes the browser revalidate on every use: always fresh at the cost of a conditional request each time, right for files that change under a stable URL (and for dev, where you want edits visible on reload). `StaticImmutable` promises the URL's content will never change, so the browser may cache it forever with no requests at all: only safe when a changed file gets a changed URL, which is what `vurl` or a bundler's content-hashed filenames provide.", + "id": "58f59f41ea0160e0" }, { - "cell_type": "code", - "execution_count": null, - "id": "27910e71", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "statd = Path(tempfile.mkdtemp())\n", "(statd/'app.css').write_text('body{}')\n", @@ -4575,14 +3950,14 @@ "stat_cli = TestClient(stat_app)\n", "test_eq(stat_cli.get('/nc/app.css').headers['cache-control'], 'no-cache')\n", "test_eq(stat_cli.get('/imm/app.css').headers['cache-control'], 'public, max-age=31536000, immutable')" - ] + ], + "id": "d107a4932dcdd8a" }, { - "cell_type": "code", - "execution_count": null, - "id": "e38fd6c7", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "#| export\n", "@flexicache(mtime_policy(arg=0))\n", @@ -4594,22 +3969,20 @@ " p = Path(root)/u.path.lstrip('/')\n", " q = f'{u.query}&' if u.query else ''\n", " return urlunsplit(u._replace(query=f'{q}v={_vhash(p)}'))\n" - ] + ], + "id": "17e13907ee30fc50" }, { - "cell_type": "markdown", - "id": "bc5b7561", "metadata": {}, - "source": [ - "Browsers use the URL as the cache key, so a URL that changes whenever the file's contents change can be cached forever: serve the mount with `StaticImmutable` and the asset costs no requests at all until it is next edited. This is the query-param version of the content-hashed filenames that asset pipelines and bundlers produce, without the build step. The hash is cached via `flexicache` with `mtime_policy`, so a call costs one `stat` and the file is only re-read after it changes. The param is inert under `no-cache` serving, so the same links work in dev with `StaticNoCache`, where the file is rechecked on each reload." - ] + "cell_type": "markdown", + "source": "Browsers use the URL as the cache key, so a URL that changes whenever the file's contents change can be cached forever: serve the mount with `StaticImmutable` and the asset costs no requests at all until it is next edited. This is the query-param version of the content-hashed filenames that asset pipelines and bundlers produce, without the build step. The hash is cached via `flexicache` with `mtime_policy`, so a call costs one `stat` and the file is only re-read after it changes. The param is inert under `no-cache` serving, so the same links work in dev with `StaticNoCache`, where the file is rechecked on each reload.", + "id": "b72b1bfca5946f5b" }, { - "cell_type": "code", - "execution_count": null, - "id": "28e4a133", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "tmp = Path(tempfile.mkdtemp())\n", "(tmp/'a.css').write_text('body{}')\n", @@ -4622,26 +3995,26 @@ "(tmp/'a.css').write_text('body{color:red}')\n", "os.utime(tmp/'a.css', (time.time()+1,)*2)\n", "assert vurl('a.css', tmp) != u" - ] + ], + "id": "8215a537819de8bd" }, { - "cell_type": "code", - "execution_count": null, - "id": "7189daf8", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "#| export\n", "from functools import wraps\n", "from inspect import signature, isawaitable" - ] + ], + "id": "1a6cbfc05998c35d" }, { - "cell_type": "code", - "execution_count": null, - "id": "7eed23b7", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "#| export\n", "def add_sig_param(f, name, typ=NoneType, kind=Parameter.KEYWORD_ONLY, default=Parameter.empty):\n", @@ -4653,14 +4026,14 @@ " f.__signature__ = sig.replace(parameters=new_params)\n", " f.__annotations__[name] = typ\n", " return f" - ] + ], + "id": "66cc946f0f8a8894" }, { - "cell_type": "code", - "execution_count": null, - "id": "9e5a9e88", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "#| export\n", "class into:\n", @@ -4683,30 +4056,26 @@ " anno = p.annotation if p.annotation is not Parameter.empty else NoneType\n", " add_sig_param(_inner, k, anno, default=p.default)\n", " return _inner" - ] + ], + "id": "ffee8e07c9b7665d" }, { - "cell_type": "markdown", - "id": "eba9a334", "metadata": {}, - "source": [ - "`into` is a decorator that composes two functions: the decorated route function and an outer \"wrapper\" function (like a layout). The route's return value is passed as positional args to the wrapper. Any keyword parameters listed in `params` are added to the route's signature, so they become available as query/form parameters. This lets you write simple routes that return just their content, while the layout and its parameters are handled automatically." - ] + "cell_type": "markdown", + "source": "`into` is a decorator that composes two functions: the decorated route function and an outer \"wrapper\" function (like a layout). The route's return value is passed as positional args to the wrapper. Any keyword parameters listed in `params` are added to the route's signature, so they become available as query/form parameters. This lets you write simple routes that return just their content, while the layout and its parameters are handled automatically.", + "id": "1d7a5679528c39d" }, { - "cell_type": "markdown", - "id": "163acb67", "metadata": {}, - "source": [ - "Here `hello` returns a single `P` tag, but `into(my_layout)` passes it into `my_layout`, which wraps it in a `Titled`. The `title` parameter is injected into `hello`'s signature so it can be set via query params." - ] + "cell_type": "markdown", + "source": "Here `hello` returns a single `P` tag, but `into(my_layout)` passes it into `my_layout`, which wraps it in a `Titled`. The `title` parameter is injected into `hello`'s signature so it can be set via query params.", + "id": "fa58fb4fd02c2db0" }, { - "cell_type": "code", - "execution_count": null, - "id": "50a9abbd", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "app,cli,rt = get_cli(FastHTML())\n", "\n", @@ -4715,54 +4084,50 @@ "@rt\n", "@into(my_layout)\n", "def hello(name:str='World'): return P(f'Hello, {name}!')" - ] + ], + "id": "3e1fe925afb7969" }, { - "cell_type": "markdown", - "id": "9aa0ac77", "metadata": {}, - "source": [ - "With no query params, `name` defaults to `'World'` and `title` defaults to `'Default'` (from `my_layout`'s own default), giving us a page titled \"Default\" containing \"Hello, World!\"." - ] + "cell_type": "markdown", + "source": "With no query params, `name` defaults to `'World'` and `title` defaults to `'Default'` (from `my_layout`'s own default), giving us a page titled \"Default\" containing \"Hello, World!\".", + "id": "6d3457d3d02d70e" }, { - "cell_type": "code", - "execution_count": null, - "id": "3a08f786", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "r = cli.get('/hello')\n", "assert 'Default' in r.text\n", "assert '

Hello, World!

' in r.text" - ] + ], + "id": "2e12f2654d9f9548" }, { - "cell_type": "markdown", - "id": "5a172800", "metadata": {}, - "source": [ - "Here, both `name` and `title` are provided as query params. `name='Jeremy'` is handled by `hello` directly, while `title='Greetings'` is the injected param that gets forwarded to `my_layout`." - ] + "cell_type": "markdown", + "source": "Here, both `name` and `title` are provided as query params. `name='Jeremy'` is handled by `hello` directly, while `title='Greetings'` is the injected param that gets forwarded to `my_layout`.", + "id": "d16aabdb9df9fc0d" }, { - "cell_type": "code", - "execution_count": null, - "id": "0fcfbf16", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "r = cli.get('/hello?name=Jeremy&title=Greetings')\n", "assert 'Greetings' in r.text\n", "assert '

Hello, Jeremy!

' in r.text" - ] + ], + "id": "f813fe19102b7fc7" }, { - "cell_type": "code", - "execution_count": null, - "id": "1960d7ff", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "#| export\n", "class MiddlewareBase:\n", @@ -4771,14 +4136,14 @@ " if scope[\"type\"] in (\"http\", \"websocket\"): return HTTPConnection(scope)\n", " await self._app(scope, receive, send)\n", " " - ] + ], + "id": "621de4f72f855409" }, { - "cell_type": "code", - "execution_count": null, - "id": "83a20f93", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "#| export\n", "class FtResponse:\n", @@ -4794,14 +4159,14 @@ " if not tasks: tasks = self.background\n", " headers = {**(self.headers or {}), **httphdrs}\n", " return self.cls(cts, status_code=self.status_code, headers=headers, media_type=self.media_type, background=tasks)" - ] + ], + "id": "a19aeb513a26811d" }, { - "cell_type": "code", - "execution_count": null, - "id": "a9e66b7d", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "@rt('/ftr')\n", "def get():\n", @@ -4814,37 +4179,20 @@ "test_eq(r.headers['location'], '/foo/1')\n", "txt = r.text\n", "assert 'Foo' in txt and '

bar

' in txt and '' in txt" - ] + ], + "id": "97242b82a893fb30" }, { - "cell_type": "markdown", - "id": "94705ca7", "metadata": {}, - "source": [ - "Test on a single background task:" - ] + "cell_type": "markdown", + "source": "Test on a single background task:", + "id": "cbc9c706e4bf24c6" }, { + "metadata": {}, "cell_type": "code", + "outputs": [], "execution_count": null, - "id": "8cf7433e", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Starting slow task\n" - ] - }, - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Finished slow task\n" - ] - } - ], "source": [ "def my_slow_task():\n", " print('Starting slow task') \n", @@ -4858,79 +4206,34 @@ "\n", "test_eq(r.status_code, 200)\n", "\n" - ] + ], + "id": "dcd54920e1965347" }, { - "cell_type": "markdown", - "id": "47c26feb", "metadata": {}, - "source": [ - "Test multiple background tasks:" - ] + "cell_type": "markdown", + "source": "Test multiple background tasks:", + "id": "9400f23cc2ac6adc" }, { - "cell_type": "code", - "execution_count": null, - "id": "76d25483", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "def increment(amount):\n", " amount = amount/1000\n", " print(f'Sleeping for {amount}s') \n", " time.sleep(amount)\n", " print(f'Slept for {amount}s') " - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "bd7cf045", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Sleeping for 0.0s\n" - ] - }, - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Slept for 0.0s\n" - ] - }, - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Sleeping for 0.001s\n" - ] - }, - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Slept for 0.001s\n" - ] - }, - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Sleeping for 0.002s\n" - ] - }, - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Slept for 0.002s\n" - ] - } ], + "id": "20ea3030ace925f8" + }, + { + "metadata": {}, + "cell_type": "code", + "outputs": [], + "execution_count": null, "source": [ "@rt\n", "def backgrounds():\n", @@ -4940,57 +4243,14 @@ "\n", "r = cli.get('/backgrounds')\n", "test_eq(r.status_code, 200)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "5310fea9", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Sleeping for 0.0s\n" - ] - }, - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Slept for 0.0s\n" - ] - }, - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Sleeping for 0.001s\n" - ] - }, - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Slept for 0.001s\n" - ] - }, - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Sleeping for 0.002s\n" - ] - }, - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Slept for 0.002s\n" - ] - } ], + "id": "eab10bb45ede6f25" + }, + { + "metadata": {}, + "cell_type": "code", + "outputs": [], + "execution_count": null, "source": [ "@rt\n", "def backgrounds2():\n", @@ -4999,67 +4259,14 @@ "\n", "r = cli.get('/backgrounds2')\n", "test_eq(r.status_code, 200)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "348f9bbd", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Sleeping for 0.0s\n" - ] - }, - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Slept for 0.0s\n" - ] - }, - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Sleeping for 0.001s\n" - ] - }, - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Slept for 0.001s\n" - ] - }, - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Sleeping for 0.002s\n" - ] - }, - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Slept for 0.002s\n" - ] - }, - { - "data": { - "text/plain": [ - "{'status': 'done'}" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } ], + "id": "67a11c47e760e088" + }, + { + "metadata": {}, + "cell_type": "code", + "outputs": [], + "execution_count": null, "source": [ "@rt\n", "def backgrounds3():\n", @@ -5069,14 +4276,14 @@ "r = cli.get('/backgrounds3')\n", "test_eq(r.status_code, 200)\n", "r.json()" - ] + ], + "id": "57f456b964a6c2b7" }, { - "cell_type": "code", - "execution_count": null, - "id": "9dc1025e", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "#| export\n", "def unqid(seeded=False):\n", @@ -5084,28 +4291,28 @@ " id4 = UUID(int=random.getrandbits(128), version=4) if seeded else uuid4()\n", " res = b64encode(id4.bytes)\n", " return '_' + res.decode().rstrip('=').translate(str.maketrans('+/', '_-'))" - ] + ], + "id": "335006dfb096cead" }, { - "cell_type": "code", - "execution_count": null, - "id": "5b67e014", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "#| export\n", "def _add_ids(s):\n", " if not isinstance(s, FT): return\n", " if not getattr(s, 'id', None): s.id = unqid()\n", " for c in s.children: _add_ids(c)" - ] + ], + "id": "637735f394562e3a" }, { - "cell_type": "code", - "execution_count": null, - "id": "1f590f25", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "#| export\n", "@patch\n", @@ -5118,14 +4325,14 @@ " for o in conns.values(): await o(s)\n", " app._send = send\n", " return send" - ] + ], + "id": "7740b43745222106" }, { - "cell_type": "code", - "execution_count": null, - "id": "a8a91edd", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "#| export\n", "devtools_loc = \"/.well-known/appspecific/com.chrome.devtools.json\"\n", @@ -5136,14 +4343,14 @@ " if not uuid: uuid = str(uuid5(NAMESPACE_URL, str(path)))\n", " @self.route(devtools_loc)\n", " def devtools(): return dict(workspace=dict(root=str(path), uuid=uuid))" - ] + ], + "id": "c31e7509d1ca707" }, { - "cell_type": "code", - "execution_count": null, - "id": "e27908c0", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "#| export\n", "@patch\n", @@ -5156,14 +4363,14 @@ " client = httpx2.AsyncClient() if asink else httpx2.Client()\n", " client.cookies.update({self.session_cookie: data.decode()})\n", " return client" - ] + ], + "id": "96cfdb7d4d31f050" }, { - "cell_type": "code", - "execution_count": null, - "id": "c845f437", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "#| export\n", "@patch\n", @@ -5172,14 +4379,14 @@ " if not cookie or cookie == 'null': return {}\n", " unsigned = itsdangerous.TimestampSigner(self.secret_key).unsign(cookie, max_age=None)\n", " return loads(b64decode(unsigned).decode())" - ] + ], + "id": "2d51142bf081806d" }, { - "cell_type": "code", - "execution_count": null, - "id": "49260e9b", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "#| export\n", "@patch\n", @@ -5195,38 +4402,37 @@ " return self.app.decode_session(cookie)\n", "\n", " return FastHTMLTestClient(self, cookies=self.get_client(**kw).cookies)" - ] + ], + "id": "6636f33a9b96f503" }, { - "cell_type": "code", - "execution_count": null, - "id": "6830083b", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "cli = app.get_testclient(auth='user1')\n", "test_eq(cli.session['auth'], 'user1')" - ] + ], + "id": "8141e15a8ce24b5f" }, { - "cell_type": "markdown", - "id": "474e14b4", "metadata": {}, - "source": [ - "## Export -" - ] + "cell_type": "markdown", + "source": "## Export -", + "id": "5551a408cd475b7" }, { - "cell_type": "code", - "execution_count": null, - "id": "d211e8e2", "metadata": {}, + "cell_type": "code", "outputs": [], + "execution_count": null, "source": [ "#| hide\n", "import nbdev\n", "nbdev.nbdev_export()" - ] + ], + "id": "a48bde6e158344c0" } ], "metadata": { From f7089e11500154760034af2797993e58dcae4c28 Mon Sep 17 00:00:00 2001 From: Renato Gomes Damas Date: Tue, 20 Oct 2026 16:18:20 -0300 Subject: [PATCH 10/14] test: add tests for request parameter alias handling --- tests/test_alias.py | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 tests/test_alias.py diff --git a/tests/test_alias.py b/tests/test_alias.py new file mode 100644 index 00000000..059fe82b --- /dev/null +++ b/tests/test_alias.py @@ -0,0 +1,42 @@ +from fasthtml.common import * +from starlette.testclient import TestClient +from typing import Annotated + +app, rt = fast_app() +cli = TestClient(app) + +@rt("/query") +def get(user_id: Annotated[str, Alias("user-id")]): return f"q:{user_id}" + +@rt("/form", methods=["post"]) +def post(user_id: Annotated[str, Alias("user-id")]): return f"f:{user_id}" + +@rt("/path/{item_id}") +def get(item_id: Annotated[int, Alias("item_id")]): return f"p:{item_id}" + +@rt("/header") +def get(x_api_key: Annotated[str, Alias("X-Api-Key")]): return f"h:{x_api_key}" + +@rt("/cookie") +def get(req, session_id: Annotated[str, Alias("session-id")]): return f"c:{session_id}" + +@rt("/int") +def get(count: Annotated[int, Alias("the-count")]): return f"i:{count + 1}" + +@rt("/plain") +def get(user_id: str): return f"plain:{user_id}" + +@rt("/missing") +def get(user_id: Annotated[str, Alias("user-id")]): return user_id + +def test_query_alias(): assert cli.get('/query?user-id=abc').text == 'q:abc' +def test_form_alias(): assert cli.post('/form', data={'user-id': 'abc'}).text == 'f:abc' +def test_path_alias(): assert cli.get('/path/7').text == 'p:7' +def test_header_alias(): assert cli.get('/header', headers={'X-Api-Key': 'k1'}).text == 'h:k1' +def test_cookie_alias(): assert cli.get('/cookie', cookies={'session-id': 's1'}).text == 'c:s1' +def test_int_alias(): assert cli.get('/int?the-count=4').text == 'i:5' +def test_plain_unchanged(): assert cli.get('/plain?user_id=z').text == 'plain:z' +def test_snake_name_not_used_for_alias(): assert cli.get('/query?user_id=abc').status_code == 400 +def test_missing_message_uses_alias(): + r = cli.get('/missing') + assert r.status_code == 400 and 'Missing required field: user-id' in r.text From 078bf8399c645a6bebdc6fa33544e458bb639de6 Mon Sep 17 00:00:00 2001 From: Renato Gomes Damas Date: Tue, 20 Oct 2026 16:43:08 -0300 Subject: [PATCH 11/14] refactor: update code cell metadata in 00_core.ipynb --- nbs/api/00_core.ipynb | 585 +++++++++++++++++++++--------------------- 1 file changed, 298 insertions(+), 287 deletions(-) diff --git a/nbs/api/00_core.ipynb b/nbs/api/00_core.ipynb index 95a8cf01..b1efc44d 100644 --- a/nbs/api/00_core.ipynb +++ b/nbs/api/00_core.ipynb @@ -6,7 +6,7 @@ "outputs": [], "execution_count": null, "source": "#| default_exp core", - "id": "7f686573b69acc40" + "id": "bc698490f70ad760" }, { "metadata": {}, @@ -15,7 +15,7 @@ "# Core\n", "> The `FastHTML` subclass of `Starlette`." ], - "id": "59798c88b0200b3c" + "id": "7cfa9456b28add27" }, { "metadata": {}, @@ -62,19 +62,19 @@ "\n", "See the [Handling Handlers tutorial](https://www.fastht.ml/docs/ref/handlers.html.md) for worked examples of the above." ], - "id": "ab4062d704000f87" + "id": "4a5c40cbd6b96a37" }, { "metadata": {}, "cell_type": "markdown", "source": "This is the source code to fasthtml. You won't need to read this unless you want to understand how things are built behind the scenes, or need full details of a particular API. The notebook is converted to the Python module [fasthtml/core.py](https://github.com/AnswerDotAI/fasthtml/blob/main/fasthtml/core.py) using [nbdev](https://nbdev.fast.ai/).", - "id": "1acd20a02bd6d35a" + "id": "a70d5d3182ca303b" }, { "metadata": {}, "cell_type": "markdown", "source": "## Imports and utils", - "id": "34bfc48a8b184299" + "id": "687079de57a42a34" }, { "metadata": {}, @@ -110,7 +110,7 @@ "from fasthtml.starlette import *\n", "from python_multipart.exceptions import MultipartParseError" ], - "id": "53afb6589c3d143e" + "id": "74eb565a6ca22027" }, { "metadata": {}, @@ -131,7 +131,7 @@ "from fastcore.net import run_sync\n", "from starlette.datastructures import UploadFile" ], - "id": "7410b06288e1fe26" + "id": "908ef33d5b949d61" }, { "metadata": {}, @@ -144,13 +144,13 @@ "\n", "empty = Parameter.empty" ], - "id": "43c1dfb348886a28" + "id": "c2e8bf6eec8515ea" }, { "metadata": {}, "cell_type": "markdown", "source": "We write source code _first_, and then tests come _after_. The tests serve as both a means to confirm that the code works and also serves as working examples. The first exported function, `parsed_date`, is an example of this pattern.", - "id": "994c8a6af6a4d489" + "id": "a48905ec29e84b05" }, { "metadata": {}, @@ -163,7 +163,7 @@ " \"Convert `s` to a datetime\"\n", " return dtparse.parse(s)" ], - "id": "459b5fc44b7c9d5e" + "id": "3db9e4e5a4a60f47" }, { "metadata": {}, @@ -171,7 +171,7 @@ "outputs": [], "execution_count": null, "source": "parsed_date('2pm')", - "id": "809da9c50103c9dd" + "id": "f0d0ab89fcf93351" }, { "metadata": {}, @@ -179,7 +179,7 @@ "outputs": [], "execution_count": null, "source": "isinstance(date.fromtimestamp(0), date)", - "id": "5e5a75f6663c14e2" + "id": "d772a5c1a3e07e1b" }, { "metadata": {}, @@ -193,7 +193,7 @@ " s = snake2camel(s)\n", " return camel2words(s, '-')" ], - "id": "fd499ac1bf5ca80c" + "id": "cbb1cc44abb83dea" }, { "metadata": {}, @@ -201,7 +201,7 @@ "outputs": [], "execution_count": null, "source": "snake2hyphens(\"snake_case\")", - "id": "788eebb4a93cd144" + "id": "45e928d3bf8a0127" }, { "metadata": {}, @@ -234,7 +234,7 @@ " res = {k:h.get(v.lower(), None) for k,v in htmx_hdrs.items()}\n", " return HtmxHeaders(**res)" ], - "id": "5c5266880608b6d1" + "id": "912545966705bf8b" }, { "metadata": {}, @@ -249,7 +249,7 @@ " async def receive(): return dict(type=\"http.request\", body=b\"\", more_body=False)\n", " return Request(scope, receive)" ], - "id": "a223b8b2def6c12f" + "id": "cdf830e0fbb7a8e5" }, { "metadata": {}, @@ -260,7 +260,7 @@ "h = test_request(headers=Headers({'HX-Request':'1'}))\n", "_get_htmx(h.headers)" ], - "id": "76cb9df3f9560f26" + "id": "f767c1bb72d9d113" }, { "metadata": {}, @@ -271,13 +271,13 @@ "#| export\n", "def _mk_list(t, v): return [t(o) for o in listify(v)]" ], - "id": "72e3945ec1dcb7ed" + "id": "63601ad8dd759b99" }, { "metadata": {}, "cell_type": "markdown", "source": "## Request and response", - "id": "13f0432b5d256410" + "id": "31e875a70b7d36a5" }, { "metadata": {}, @@ -288,7 +288,7 @@ "#| export\n", "fh_cfg = AttrDict(indent=True)" ], - "id": "64dbed7ee2309943" + "id": "cbc801d046d7d084" }, { "metadata": {}, @@ -304,7 +304,7 @@ " if anno is empty and arg.lower() not in _special_names and not any(s.startswith(arg.lower()) for s in ('request','session')): return f\"`{arg}` has no type annotation and is not a recognised special name, so is ignored.\"\n", " if isinstance(anno, type) and not get_origin(anno) and issubclass(anno, (list, tuple)) and not _is_body(anno): return f\"`{arg}` uses bare `{anno.__name__}` annotation, so is ignored (use e.g. `{anno.__name__}[str]` instead).\"" ], - "id": "174eac262617a991" + "id": "a226ee3cccb2519e" }, { "metadata": {}, @@ -325,7 +325,7 @@ " if not isinstance(o, (str,list,tuple)): return o\n", " return res(o[-1]) if isinstance(o,(list,tuple)) else res(o)" ], - "id": "b61bf0b9981ede39" + "id": "9ce04062c728e12d" }, { "metadata": {}, @@ -346,7 +346,7 @@ "test_eq(_fix_anno(list[str], []), [])\n", "test_eq(_fix_anno(Optional[list[str]], '1'), ['1'])" ], - "id": "1734c816b8331d79" + "id": "ede3b755b5964d1c" }, { "metadata": {}, @@ -364,7 +364,7 @@ " if not anno: return v\n", " return _fix_anno(anno, v)" ], - "id": "d1cd459b43ebdeb8" + "id": "e9cff1c16a6133bf" }, { "metadata": {}, @@ -377,7 +377,7 @@ "test_eq(_form_arg('l', \"1\", d), [1])\n", "test_eq(_form_arg('l', [\"1\",\"2\"], d), [1,2])" ], - "id": "c56632e237956f69" + "id": "8fd54d1e73b50c65" }, { "metadata": {}, @@ -391,7 +391,7 @@ " \"A response header as a k,v pair\"\n", " k:str;v:str" ], - "id": "e02eb8ef77a0ed27" + "id": "ccae4a3e3396de7c" }, { "metadata": {}, @@ -405,7 +405,7 @@ "htmx_resps = dict(location=None, push_url=None, redirect=None, refresh=None, replace_url=None,\n", " reswap=None, retarget=None, reselect=None, trigger=None, trigger_after_settle=None, trigger_after_swap=None)" ], - "id": "20c90293417cb2af" + "id": "475fcdfb7f60b95f" }, { "metadata": {}, @@ -413,7 +413,7 @@ "outputs": [], "execution_count": null, "source": "_to_htmx_header('trigger_after_settle')", - "id": "64616ebfdd4b64bb" + "id": "80392b12e1020f0b" }, { "metadata": {}, @@ -428,7 +428,7 @@ " res = tuple(HttpHeader(_to_htmx_header(k), v) for k,v in kwargs.items())\n", " return res[0] if len(res)==1 else res" ], - "id": "96914eebba4f02bc" + "id": "862adead1ff6fd91" }, { "metadata": {}, @@ -436,7 +436,7 @@ "outputs": [], "execution_count": null, "source": "HtmxResponseHeaders(trigger_after_settle='hi')", - "id": "2189b2baeb94dd0d" + "id": "9cf582da2f77eb69" }, { "metadata": {}, @@ -450,7 +450,7 @@ " if is_namedtuple(anno): return {o:str for o in anno._fields}\n", " return get_annotations(anno)" ], - "id": "d91ef3bd135dc3ee" + "id": "a31232134dbe2ac" }, { "metadata": {}, @@ -462,7 +462,7 @@ "class Foo: a:int; b:str\n", "_annotations(Foo)" ], - "id": "d4be2f3056e3f950" + "id": "717938adccebe4f3" }, { "metadata": {}, @@ -473,7 +473,7 @@ "Point = namedtuple('Point', ['x', 'y'])\n", "_annotations(Point)" ], - "id": "d2afd93effac57ad" + "id": "c49e5997904e333d" }, { "metadata": {}, @@ -484,7 +484,7 @@ "#| export\n", "def _is_body(anno): return issubclass(anno, (dict,ns)) or hasattr(anno,'__from_request__') or _annotations(anno)" ], - "id": "ffd54d552801d9a5" + "id": "acf8e46c0b78a844" }, { "metadata": {}, @@ -500,7 +500,7 @@ " o = form.getlist(k)\n", " return o[0] if len(o) == 1 else o if o else None" ], - "id": "9008844db08f88f2" + "id": "c47ddb9dca284510" }, { "metadata": {}, @@ -514,7 +514,7 @@ " if isinstance(form, dict): return form\n", " return {k: _formitem(form, k) for k in form}" ], - "id": "cff090e30c5ca11a" + "id": "30a9fdb45d78cc71" }, { "metadata": {}, @@ -528,7 +528,7 @@ "test_eq(res['a'], [1,2])\n", "test_eq(res['b'], 0)" ], - "id": "8e046d5aa0ad19ec" + "id": "1620a03b5b53c9ae" }, { "metadata": {}, @@ -539,7 +539,7 @@ "#| export\n", "DEF_MAXPART = 100*1024*1024" ], - "id": "319a6c62cc3e35ed" + "id": "f1b4827ca0fe2157" }, { "metadata": {}, @@ -566,13 +566,13 @@ " return res\n", " return await req.form(max_part_size=maxpart)" ], - "id": "9c5cdcc778cc38a7" + "id": "1054d6149d8720ec" }, { "metadata": {}, "cell_type": "markdown", "source": "Use the special `__from_request__` class method for custom creation:", - "id": "af8b65337d831e72" + "id": "2280bfd557b15769" }, { "metadata": {}, @@ -586,7 +586,7 @@ " @classmethod\n", " def __from_request__(cls, data, req): return cls(data)" ], - "id": "a9a4f860d46ba408" + "id": "551de704c7ecce25" }, { "metadata": {}, @@ -600,7 +600,7 @@ "async def mock_form(**kwargs): return FormData({'a':1})\n", "req.form = mock_form" ], - "id": "dd2182af86fb2578" + "id": "2d97d6131b208778" }, { "metadata": {}, @@ -624,7 +624,7 @@ " cargs = {k: _form_arg(k, v, d) for k, v in data.items() if not d or k in d}\n", " return anno(**cargs)" ], - "id": "23f9fadd08c3c28c" + "id": "92dfc839766cc4a6" }, { "metadata": {}, @@ -641,13 +641,13 @@ " def __call__(self, norm=None, **kw): return kw if self.isapi else norm\n", " def __bool__(self): return bool(self.isapi)" ], - "id": "afa2e38d1b854c81" + "id": "fed371a8d4196a6e" }, { "metadata": {}, "cell_type": "markdown", "source": "Routes often need to return different responses depending on whether the request comes from a browser or an API client. The `api:ApiReturn` parameter handles this automatically — add it to any route signature and call it with two arguments: the API response and the browser response. If the request's `Accept` header is `application/json` then a dict of the kwargs is returned, otherwise, the first value is returned. For example, `return api(Redirect('/records'), id=record.id)` returns {'id':id} for API callers and a redirect for the browser. This keeps your route logic in one place instead of splitting it across separate endpoints.", - "id": "ec73cbbd214917ea" + "id": "bf11cb6047e4bbcc" }, { "metadata": {}, @@ -663,7 +663,7 @@ " res = json.dumps(content, ensure_ascii=False, allow_nan=False, indent=None, separators=(\",\",\":\"), default=_default)\n", " return res.encode(\"utf-8\")\n" ], - "id": "6fc0c7f6b7e307fe" + "id": "53fde9431c4751d9" }, { "metadata": {}, @@ -684,7 +684,7 @@ "response = client.post('/', data=d)\n", "print(response.json())" ], - "id": "91a217829d3e79f9" + "id": "42c96871a0ed3570" }, { "metadata": {}, @@ -701,13 +701,13 @@ "res = client.post('/', json={'a':1}) # non-empty json still parses (behavior preserved)\n", "test_eq(res.json(), {'a':1})" ], - "id": "126d0dcf0eb89218" + "id": "e28834e8078136ba" }, { "metadata": {}, "cell_type": "markdown", "source": "A malformed multipart body (here the opening boundary isn't followed by CRLF) is the client's error, so `parse_form` answers 400 rather than letting the parser's exception surface as a 500:", - "id": "bd7f8488c0910f52" + "id": "ae77b32f318ad7c2" }, { "metadata": {}, @@ -720,13 +720,13 @@ "test_eq(res.status_code, 400)\n", "res.text" ], - "id": "71c4ef54948643a3" + "id": "ba7a4c7ff2044fba" }, { "metadata": {}, "cell_type": "markdown", "source": "A JSON body that does not decode, or decodes to something other than an object (an array, say), cannot supply route parameters, so it is refused with 400 rather than failing inside the form conversion:", - "id": "f785db5c4a5d10f2" + "id": "4b4c9ac6bb612971" }, { "metadata": {}, @@ -740,7 +740,7 @@ "test_eq(res.status_code, 400)\n", "res.text" ], - "id": "2079e9d02dd2e49c" + "id": "7f41ac48f4bd638" }, { "metadata": {}, @@ -752,7 +752,7 @@ "client = TestClient(Starlette(routes=[Route('/', f, methods=['GET'])]))\n", "client.get('/?x=1&x=2').text" ], - "id": "bc54b0a9ba395e42" + "id": "9764bf75c1614912" }, { "metadata": {}, @@ -820,7 +820,18 @@ " if isinstance(conn, Request): raise HTTPException(404, f\"{conn.url.path}: {e}\") from None\n", " raise" ], - "id": "8e679f81c025a2e6" + "id": "e40a106c3f3f85fc" + }, + { + "metadata": {}, + "cell_type": "code", + "outputs": [], + "execution_count": null, + "source": [ + "data = form2dict(await parse_form(req))\n", + "await _from_body(req, p, data)" + ], + "id": "92acee97a091aaa5" }, { "metadata": {}, @@ -833,7 +844,7 @@ " if conn.query_params: data |= dict(conn.query_params)\n", " return {arg:await _find_p(conn, data, hdrs, arg, p) for arg,p in params.items()}" ], - "id": "d98c2374a04c1424" + "id": "bf313685869a8006" }, { "metadata": {}, @@ -844,7 +855,7 @@ "data = form2dict(await parse_form(req))\n", "await _from_body(req, p, data)" ], - "id": "1895949b223f331d" + "id": "a32b68e1d3bc55b0" }, { "metadata": {}, @@ -857,7 +868,7 @@ " data = form2dict(await parse_form(req))\n", " return await _find_ps(req, data, req.headers, params)" ], - "id": "e5f9b252b5404d6" + "id": "b419de64cde702c1" }, { "metadata": {}, @@ -877,7 +888,7 @@ "test_eq(r.status_code, 200)\n", "print(r.text)" ], - "id": "212c21983334789e" + "id": "1c872b17d28ab528" }, { "metadata": {}, @@ -895,7 +906,7 @@ "response = client.post('/?a=1', data=d)\n", "print(response.text)" ], - "id": "3aab2026066508b8" + "id": "4f9212b9a87ad40f" }, { "metadata": {}, @@ -913,7 +924,7 @@ "response = client.post('/?a=1', data=d)\n", "print(response.text)" ], - "id": "ad76da242022e3f4" + "id": "bdad60519a7d7b2e" }, { "metadata": {}, @@ -935,19 +946,19 @@ "client = TestClient(Starlette(routes=[Route('/', f, methods=['POST'])]))\n", "client.post('/', headers={'Accept': 'application/json'}).text" ], - "id": "ead1df177cd0001" + "id": "b5767c849a371a0e" }, { "metadata": {}, "cell_type": "markdown", "source": "**Missing Request Params**", - "id": "db783b911aea310d" + "id": "db437a1989241169" }, { "metadata": {}, "cell_type": "markdown", "source": "If a request param has a default value (e.g. `a:str=''`), the request is valid even if the user doesn't include the param in their request.", - "id": "8774cb8b857934eb" + "id": "de4ad9e40e66bfb7" }, { "metadata": {}, @@ -965,13 +976,13 @@ "response = client.post('/', json={}) # no param in request\n", "print(response.text)" ], - "id": "624c7f99944813aa" + "id": "55c862659aadd36c" }, { "metadata": {}, "cell_type": "markdown", "source": "If we remove the default value and re-run the request, we should get the following error `Missing required field: a`.", - "id": "83ffd4d5f69ee8e3" + "id": "308deaafd80faab3" }, { "metadata": {}, @@ -989,7 +1000,7 @@ "response = client.post('/', json={}) # no param in request\n", "print(response.text)" ], - "id": "454d528731449c" + "id": "659f5f100851b8bf" }, { "metadata": {}, @@ -1007,7 +1018,7 @@ " else: result.append(item)\n", " return tuple(result)" ], - "id": "693922c3e46c7754" + "id": "c03c445284151c7c" }, { "metadata": {}, @@ -1019,7 +1030,7 @@ "test_eq(flat_xt([x, x, [x,x]]), (x,)*4)\n", "test_eq(flat_xt(x), (x,))" ], - "id": "581fbbf507982aae" + "id": "b194b91df7d94eeb" }, { "metadata": {}, @@ -1033,7 +1044,7 @@ " def __init__(self, f, skip=None): self.f,self.skip = f,skip or []\n", " def __repr__(self): return f'Beforeware({self.f}, skip={self.skip})'" ], - "id": "6192cec3c0df1bb3" + "id": "6b7dbc73c0ee9956" }, { "metadata": {}, @@ -1045,7 +1056,7 @@ "async def _handle(f, /, *args, **kwargs):\n", " return (await f(*args, **kwargs)) if is_async_callable(f) else await run_in_threadpool(f, *args, **kwargs)" ], - "id": "8ec98475a0a5c7d6" + "id": "baf21aa39d330caa" }, { "metadata": {}, @@ -1056,13 +1067,13 @@ "async def _f(f): return f\"got {f}\"\n", "test_eq(await _handle(_f, f='hello'), 'got hello')" ], - "id": "da268ae91d91d9bc" + "id": "dd14420eb9df34c3" }, { "metadata": {}, "cell_type": "markdown", "source": "## Websockets / SSE", - "id": "92d3135c4ad6710f" + "id": "c7e4a0ee7bcfeeb7" }, { "metadata": {}, @@ -1076,7 +1087,7 @@ " hdrs = Headers({k.lower():v for k,v in raw.items() if v is not None})\n", " return await _find_ps(ws, data, hdrs, params)" ], - "id": "5f2702274bb51006" + "id": "ff2e3560134d8625" }, { "metadata": {}, @@ -1112,7 +1123,7 @@ " cls.on_receive = _recv\n", " return cls" ], - "id": "9419cd0224cd98c2" + "id": "18b7eece28a161e6" }, { "metadata": {}, @@ -1128,7 +1139,7 @@ " data = ws.receive_text()\n", " assert data == 'Message text was: Hi!', data" ], - "id": "bc7c575a83684d5b" + "id": "4ba9a76b79dde97b" }, { "metadata": {}, @@ -1143,7 +1154,7 @@ " data = ws.receive_text()\n", " assert data == 'trigger: my-btn', data\n" ], - "id": "42a74b181d3b6a8f" + "id": "3c9f31d17d2c4f38" }, { "metadata": {}, @@ -1156,7 +1167,7 @@ " \"Create a text/event-stream response from `s`\"\n", " return StreamingResponse(s, media_type=\"text/event-stream\")" ], - "id": "741044b3e551225c" + "id": "e6863a75509ad30f" }, { "metadata": {}, @@ -1176,13 +1187,13 @@ " self._orig_handle_exit(*args, **kwargs)\n", " return event" ], - "id": "da2d506cff9cd847" + "id": "45597971e1e50d5e" }, { "metadata": {}, "cell_type": "markdown", "source": "## Routing and application", - "id": "a4eeb45c2f82f3ff" + "id": "7ec729996815fee2" }, { "metadata": {}, @@ -1195,7 +1206,7 @@ " \"Create a URI by URL-encoding `_arg` and appending query parameters from `kwargs`\"\n", " return f\"{quote(_arg)}/{urlencode(kwargs, doseq=True)}\"" ], - "id": "184283f3ee5d49ba" + "id": "530eae6fbdd9539c" }, { "metadata": {}, @@ -1209,7 +1220,7 @@ " arg,_,kw = s.partition('/')\n", " return unquote(arg), {k:v[0] for k,v in parse_qs(kw).items()}" ], - "id": "ccfedf12c80ff96" + "id": "e2a698806339055" }, { "metadata": {}, @@ -1220,7 +1231,7 @@ "#| export\n", "from starlette.convertors import StringConvertor" ], - "id": "fd09bc5e426f4a9c" + "id": "4807df742dbb80d1" }, { "metadata": {}, @@ -1238,7 +1249,7 @@ " # assert value, \"Must not be empty\" # line removed due to errors\n", " return value" ], - "id": "7b7ad4249ea81211" + "id": "2d21bc37c076b635" }, { "metadata": {}, @@ -1252,7 +1263,7 @@ " lp = self.scope['app'].url_path_for(name, **path_params)\n", " return URLPath(f\"{self.scope['root_path']}{lp}\", lp.protocol, lp.host)" ], - "id": "70c8ec8b0a8ab19f" + "id": "770c2ff543026748" }, { "metadata": {}, @@ -1286,7 +1297,7 @@ " _find_targets(req, resp)\n", " return to_xml(resp, indent=indent)" ], - "id": "3f97f1ed8c754dff" + "id": "3c4b16489e6e3d54" }, { "metadata": {}, @@ -1297,7 +1308,7 @@ "#| export\n", "_iter_typs = (tuple,list,map,filter,range,types.GeneratorType)" ], - "id": "fb23ee8a4bdf6ffc" + "id": "131028d5ce8bec84" }, { "metadata": {}, @@ -1316,7 +1327,7 @@ " else: result.append(item)\n", " return tuple(result)" ], - "id": "f729e85becb6bbb6" + "id": "783da4cec6e383e5" }, { "metadata": {}, @@ -1329,7 +1340,7 @@ " \"Default Body wrap function which just returns the content\"\n", " return c" ], - "id": "3e5a0b56fa0c4857" + "id": "6d43e7902f33976c" }, { "metadata": {}, @@ -1346,7 +1357,7 @@ " body = Body(body_wrap(*bw_args), *flat_xt(req.ftrs), **req.bodykw)\n", " return Html(Head(*heads, *flat_xt(req.hdrs)), body, **req.htmlkw)" ], - "id": "b8e014df4ebb00b3" + "id": "a0a10c614c784090" }, { "metadata": {}, @@ -1355,7 +1366,7 @@ "Render fragment if `HX-Request` header is _present_ and\n", " `HX-History-Restore-Request` header is _absent._" ], - "id": "c42f6fb487aceee5" + "id": "156bef4057dde28c" }, { "metadata": {}, @@ -1369,7 +1380,7 @@ " if resp and any(getattr(o, 'tag', '')=='html' for o in resp): return True\n", " return 'hx-request' in req.headers and 'hx-history-restore-request' not in req.headers" ], - "id": "7ba6db1142901c4d" + "id": "e0f01932b6543d7c" }, { "metadata": {}, @@ -1394,7 +1405,7 @@ " if len(resp)==1: resp = resp[0]\n", " return resp,kw" ], - "id": "58f36aba629b2268" + "id": "6412519625d5d511" }, { "metadata": {}, @@ -1418,7 +1429,7 @@ " resp = respond(req, [*heads, *title, *_canonical(req)], bdy)\n", " return _to_xml(req, resp, indent=fh_cfg.indent)" ], - "id": "a005b335ea8a4c04" + "id": "2348b0e1d611ff62" }, { "metadata": {}, @@ -1431,7 +1442,7 @@ " \"Check if response is a FastTag-compatible type\"\n", " return isinstance(resp, _iter_typs+(HttpHeader,FT)) or hasattr(resp, '__ft__')" ], - "id": "73c48c2cb1072a7e" + "id": "677001d8c8f92420" }, { "metadata": {}, @@ -1459,7 +1470,7 @@ " cls = HTMLResponse\n", " return cls(resp, status_code=status_code, **kw)" ], - "id": "7c02e80fed13238e" + "id": "d2f2b62c8845f99c" }, { "metadata": {}, @@ -1475,7 +1486,7 @@ " if 'hx-request' in req.headers: return HtmxResponseHeaders(redirect=self.loc)\n", " return RedirectResponse(self.loc, status_code=303)" ], - "id": "896b46c4aa03192c" + "id": "688f836678719393" }, { "metadata": {}, @@ -1489,7 +1500,7 @@ " wreq = await _wrap_req(req, params)\n", " return await _handle(f, **wreq)" ], - "id": "9b9774380fb5223c" + "id": "68a4d195b0f137e9" }, { "metadata": {}, @@ -1517,13 +1528,13 @@ " \"multipart\": \"https://cdn.jsdelivr.net/npm/htmx.org@4.0.0/dist/ext/hx-multipart.min.js\"\n", "}" ], - "id": "5df474a1953c5134" + "id": "b0b15a25a1f826d8" }, { "metadata": {}, "cell_type": "markdown", "source": "The FastHTML `exts` param supports the following:", - "id": "d2f9aef7815d59bb" + "id": "6b23ee6fde5e5b4b" }, { "metadata": {}, @@ -1531,7 +1542,7 @@ "outputs": [], "execution_count": null, "source": "print(' '.join(htmx_exts))", - "id": "fe8fdb5cd2c94da9" + "id": "e4fbd2b25f5cb6ae" }, { "metadata": {}, @@ -1548,7 +1559,7 @@ "viewport = Meta(name=\"viewport\", content=\"width=device-width, initial-scale=1, viewport-fit=cover\")\n", "charset = Meta(charset=\"utf-8\")" ], - "id": "ab5aae7c786f4db0" + "id": "953ab02f6f985c28" }, { "metadata": {}, @@ -1566,7 +1577,7 @@ " fname.write_text(key)\n", " return key" ], - "id": "fd36cd44687c2273" + "id": "6054a224e78e9366" }, { "metadata": {}, @@ -1579,7 +1590,7 @@ " \"Wrap non-list item in a list, returning empty list if None\"\n", " return [] if not o else list(o) if isinstance(o, (tuple,list)) else [o]" ], - "id": "97ae79dd8df934d9" + "id": "57fd615f7415afa8" }, { "metadata": {}, @@ -1597,7 +1608,7 @@ " return _resp(req, res, status_code=status_code)\n", " return _f" ], - "id": "440490e465c515b4" + "id": "417f41f9a2b48a07" }, { "metadata": {}, @@ -1617,13 +1628,13 @@ " # encode query params\n", " return p + ('?' + urlencode({k:'' if v in (False,None) else v for k,v in kw.items()},doseq=True) if kw else '')" ], - "id": "8c482e84ada42852" + "id": "3ac78cbb40aa5e1e" }, { "metadata": {}, "cell_type": "markdown", "source": "`qp` adds query parameters to route path strings", - "id": "2b1d80a716c0adef" + "id": "d3c28cb2f39549c7" }, { "metadata": {}, @@ -1631,7 +1642,7 @@ "outputs": [], "execution_count": null, "source": "vals = dict(a=5, b=False, c=[1,2], d='bar', e=None, ab=42)", - "id": "54be93910e6e66ba" + "id": "1e90b2548c207f5" }, { "metadata": {}, @@ -1642,13 +1653,13 @@ "res = qp('/foo', **vals)\n", "test_eq(res, '/foo?a=5&b=&c=1&c=2&d=bar&e=&ab=42')" ], - "id": "a7000a851f7ec0b1" + "id": "4bb2dd90d99c0f69" }, { "metadata": {}, "cell_type": "markdown", "source": "`qp` checks to see if each param should be sent as a query parameter or as part of the route, and encodes that properly.", - "id": "9caeec84af6b57b9" + "id": "1af3b977e4b6e939" }, { "metadata": {}, @@ -1660,7 +1671,7 @@ "res = qp(path, **vals)\n", "test_eq(res, '/foo/5/bar/42?b=&c=1&c=2&e=')" ], - "id": "37b1595d560ee414" + "id": "14bcc36e075308b5" }, { "metadata": {}, @@ -1681,7 +1692,7 @@ " elif htmx: hdrs = [htmxsrc,fhjsscr] + hdrs\n", " return [charset, viewport] + hdrs" ], - "id": "6a347c42c3a0b6b8" + "id": "8687262d8af34d50" }, { "metadata": {}, @@ -1714,7 +1725,7 @@ " };\n", "\"\"\"))\n" ], - "id": "7de7d4d9ce75b85d" + "id": "4c5e7deacc17f2dd" }, { "metadata": {}, @@ -1749,7 +1760,7 @@ "\n", " def on_event(self, event_type): return lambda f: (getattr(self, event_type)).append(f)" ], - "id": "852e2ec0c0969f52" + "id": "5fcae44026df7b16" }, { "metadata": {}, @@ -1796,13 +1807,13 @@ "\n", " def on_event(self, event_type): return self.lifespan.on_event(event_type)" ], - "id": "8e95f37034125b68" + "id": "e7a1793e81819075" }, { "metadata": {}, "cell_type": "markdown", "source": "### Routes", - "id": "9fc92122a2fa70f2" + "id": "6e4e5231cea40245" }, { "metadata": {}, @@ -1828,7 +1839,7 @@ " methods = sorted(self.methods or [])\n", " return f\"{self.__class__.__name__}(path={self.path!r}, name={self.name!r}, methods={methods!r}, host={self.host!r})\"" ], - "id": "fe44229b6931a496" + "id": "fee720e4fcd081ab" }, { "metadata": {}, @@ -1848,7 +1859,7 @@ "test_eq(cli.get('/', headers={'host': 'auth.example.com'}).text, 'auth page')\n", "print('all passed')" ], - "id": "3c04fe56abdc47fa" + "id": "6e3938b28bfa688f" }, { "metadata": {}, @@ -1864,7 +1875,7 @@ "test_eq(cli.get('/hello', headers={'host': 'other.mysite.com'}).text, 'normal hello')\n", "print('all passed')" ], - "id": "654aac80d680d4eb" + "id": "68eee5aa5ce04ade" }, { "metadata": {}, @@ -1883,7 +1894,7 @@ " self.router.routes.append(route)\n", " self.router.routes.sort(key=lambda r: not getattr(r, 'host', None))\n" ], - "id": "18175f9ddfa24df4" + "id": "761915f262a753d4" }, { "metadata": {}, @@ -1894,7 +1905,7 @@ "#| export\n", "all_meths = 'get post put delete patch head trace options'.split()" ], - "id": "c00f976494575cc" + "id": "62590e9b8aa56156" }, { "metadata": {}, @@ -1931,7 +1942,7 @@ " return _resp(req, resp, sig.return_annotation)\n", " return _f" ], - "id": "4837ef8ced64c5e0" + "id": "8b820ee5ecd21e1c" }, { "metadata": {}, @@ -1949,7 +1960,7 @@ " self.add_route(route)\n", " return func" ], - "id": "154ea30b2e45f577" + "id": "d23d12b26b62e05" }, { "metadata": {}, @@ -1964,7 +1975,7 @@ " def f(func=noop): return self._add_ws(func, path, conn, disconn, name=name, middleware=middleware)\n", " return f" ], - "id": "5655582e8b8129c6" + "id": "c6597341785b1226" }, { "metadata": {}, @@ -1978,7 +1989,7 @@ " \"Add a websocket route at `path` (Starlette-compatible API)\"\n", " return self._add_ws(func, path, conn, disconn, name=name, middleware=middleware)" ], - "id": "bb318a080450cf8c" + "id": "e9208c48e6a7d964" }, { "metadata": {}, @@ -2000,7 +2011,7 @@ "\n", " return _lf()" ], - "id": "a294e823478edca7" + "id": "5803286e07e2dd6c" }, { "metadata": {}, @@ -2013,7 +2024,7 @@ " \"Get name of function `f` using '_' to join nested function names\"\n", " return f.__qualname__.replace('..', '_')" ], - "id": "ee7941c6d76afd9e" + "id": "61504e932bcb6453" }, { "metadata": {}, @@ -2025,7 +2036,7 @@ " def g(): ...\n", " return g" ], - "id": "67a112ba5ba9ed0d" + "id": "459aa1caff394061" }, { "metadata": {}, @@ -2036,7 +2047,7 @@ "func = f()\n", "nested_name(func)" ], - "id": "e04010a30af82a09" + "id": "c3311e187ab0c525" }, { "metadata": {}, @@ -2056,7 +2067,7 @@ " if handler: self._add_route(handler, path, meth, name, include_in_schema, body_wrap, host=host, before=before)\n", " return lf" ], - "id": "ebb18855aabae4a3" + "id": "79202eff3271765a" }, { "metadata": {}, @@ -2089,7 +2100,7 @@ " lf.__routename__ = n\n", " return lf" ], - "id": "ce6f387e5f02d9db" + "id": "519bd9038c86b0d7" }, { "metadata": {}, @@ -2107,7 +2118,7 @@ "\n", "for o in all_meths: setattr(FastHTML, o, partialmethod(FastHTML.route, methods=o))" ], - "id": "112b50b015b12164" + "id": "25ae3aa5f868f44a" }, { "metadata": {}, @@ -2121,7 +2132,7 @@ "\n", "foo.to(a='bar', b=[1,2])" ], - "id": "dff8e8a4a56cf236" + "id": "b10bfcb7a593ee05" }, { "metadata": {}, @@ -2134,13 +2145,13 @@ "\n", "foo.to(a='bar', b=[1,2])" ], - "id": "37009106fa07a942" + "id": "fbe6c053bf35cb87" }, { "metadata": {}, "cell_type": "markdown", "source": "### Utils", - "id": "16d546c2d4b56c7f" + "id": "f2ed69bbaf963475" }, { "metadata": {}, @@ -2155,7 +2166,7 @@ " if inspect.isasyncgenfunction(value): value = contextlib.asynccontextmanager(value)\n", " self.router.lifespan_context = value" ], - "id": "7dadb462ba00d11c" + "id": "8395cef9c2dea921" }, { "metadata": {}, @@ -2189,13 +2200,13 @@ " print('Link: '+ S.light_red.bold(link))\n", " run(f'{appname}:{app}', host=host, port=port, reload=reload, **kwargs)" ], - "id": "c36b7185c1679ba5" + "id": "949365706b509933" }, { "metadata": {}, "cell_type": "markdown", "source": "`procs` runs the app as that many processes on consecutive ports from `port`, each with its own reload supervisor, and defaults to the `PROCS` environment variable. `serve` re-executes the script once per process with `FH_PROCNUM` set to its number, which is also the guard against a child spawning again. An app reads `FH_PROCNUM` for work that only one process should do, such as a background job: it is `'0'` in the first process, and unset in an ordinary single-process run. A reverse proxy in front of the ports decides how requests reach them.", - "id": "b9e62008c275f97b" + "id": "944609fe9b5f5360" }, { "metadata": {}, @@ -2210,13 +2221,13 @@ " signal.signal(signal.SIGTERM, lambda *a: [p.terminate() for p in ps])\n", " for p in ps: p.wait()" ], - "id": "e35a3b4cdd465a37" + "id": "9923dbe3e6937f09" }, { "metadata": {}, "cell_type": "markdown", "source": "Starlette does not cancel a running handler when a client disconnects: the disconnect is only visible as an `http.disconnect` message on the ASGI receive channel, which ordinary handlers never read. `until_disconnect` races a coroutine against that message, cancelling the work if the client goes away first.", - "id": "24c42a8e514a9e5f" + "id": "c6739d867595760d" }, { "metadata": {}, @@ -2239,13 +2250,13 @@ " watch.cancel()\n", " if not work.done(): work.cancel()" ], - "id": "42ca8bdf84326b3b" + "id": "d6f51e6ddabb5426" }, { "metadata": {}, "cell_type": "markdown", "source": "`cancel_on_disconnect` applies this to a route handler. `splice_sig` adds a private `Request`-annotated parameter to the exposed signature, which FastHTML fills with the connection, so the handler's own parameters are unchanged. It requires an async handler, since a sync handler runs in a threadpool and cannot be cancelled.", - "id": "d6f88d179121010f" + "id": "8987f8795854b0d3" }, { "metadata": {}, @@ -2267,7 +2278,7 @@ " return await (asyncio.wait_for(c, timeout) if timeout is not None else c)\n", " return splice_sig(_f, f)" ], - "id": "27f2e4665ebf5bbc" + "id": "9b289597ccc85bb0" }, { "metadata": {}, @@ -2288,7 +2299,7 @@ "\n", "for o in ('get', 'post', 'delete', 'put', 'patch', 'options'): setattr(Client, o, partialmethod(Client._sync, o))" ], - "id": "8db5fe95c7d00bec" + "id": "2d9f445812e61010" }, { "metadata": {}, @@ -2301,19 +2312,19 @@ "\n", "cli.get('/').text" ], - "id": "ad12879dd1f19e35" + "id": "a0d50c343884f7" }, { "metadata": {}, "cell_type": "markdown", "source": "Note that you can also use Starlette's `TestClient` instead of FastHTML's `Client`. They should be largely interchangable.", - "id": "a67770455c7eb2b8" + "id": "acbf8b7311f723fd" }, { "metadata": {}, "cell_type": "markdown", "source": "## FastHTML Tests", - "id": "f8a6739566557720" + "id": "1ace95eeec5d7233" }, { "metadata": {}, @@ -2321,7 +2332,7 @@ "outputs": [], "execution_count": null, "source": "def get_cli(app): return app,TestClient(app),app.route", - "id": "563e9f037bfba8a1" + "id": "11278015a711f50" }, { "metadata": {}, @@ -2329,7 +2340,7 @@ "outputs": [], "execution_count": null, "source": "app,cli,rt = get_cli(FastHTML(secret_key='soopersecret'))", - "id": "541824a436755f55" + "id": "876cfcb58fff09be" }, { "metadata": {}, @@ -2348,7 +2359,7 @@ "\n", "foo.to(param='value')" ], - "id": "c639800adf059ebf" + "id": "d223d27ab2024726" }, { "metadata": {}, @@ -2364,7 +2375,7 @@ "assert \"Goodbye World\" in cli.get('/foo', headers={'host': 'test.foo'}).text\n", "assert \"Hello World\" in cli.get('/foo').text" ], - "id": "84739e25115b6885" + "id": "e9ad23318cd58f72" }, { "metadata": {}, @@ -2377,7 +2388,7 @@ "\n", "foo.to(param='value')" ], - "id": "a9ab959322b3c533" + "id": "845c8d8cd8b678e2" }, { "metadata": {}, @@ -2393,7 +2404,7 @@ "txt = cli.get('/xt2').text\n", "assert 'FastHTML page' in txt and '

bar

' in txt and '' in txt" ], - "id": "4b7beef96901eff5" + "id": "ad7c328b17fdf13b" }, { "metadata": {}, @@ -2405,7 +2416,7 @@ " if hx: kwargs['headers'] = {'hx-request':\"1\"}\n", " test_eq(getattr(cli, meth)(path, **kwargs).text, exp)" ], - "id": "772f8f233bfdf3a0" + "id": "840a147f46b96daa" }, { "metadata": {}, @@ -2427,7 +2438,7 @@ "test_eq(cli.delete('/class-cards/abc').text, 'delete abc')\n", "test_eq(CardMethods.to(id='xyz'), '/class-cards/xyz')" ], - "id": "a3cba3e1f15e799a" + "id": "14d777ba36c4523e" }, { "metadata": {}, @@ -2442,7 +2453,7 @@ "test_eq(cli.get('/things?id=7').text, 'thing 7')\n", "test_eq(Things.to(id=7), '/things?id=7')" ], - "id": "97b51681c70ff08" + "id": "89010e5a319a1ee" }, { "metadata": {}, @@ -2456,7 +2467,7 @@ "r = cli.get('/hi')\n", "r.text" ], - "id": "b0d1876823809add" + "id": "ab04bc8df2f0627c" }, { "metadata": {}, @@ -2469,7 +2480,7 @@ "\n", "cli.post('/hi').text" ], - "id": "afc2ab1803fa418a" + "id": "87f365d396f69614" }, { "metadata": {}, @@ -2482,7 +2493,7 @@ "\n", "cli.get('/hostie').text" ], - "id": "a475f9d4844d8a3f" + "id": "c2f7aff939dc9838" }, { "metadata": {}, @@ -2505,7 +2516,7 @@ "assert 'Message text was: Hi! with session bar' in data\n", "print(data)" ], - "id": "3177015fbac381ec" + "id": "67c8fd44c79ba121" }, { "metadata": {}, @@ -2518,7 +2529,7 @@ "\n", "cli.post('/yoyo').text" ], - "id": "6b0d7ef1d4bd445d" + "id": "11bf1da78fa14eed" }, { "metadata": {}, @@ -2530,7 +2541,7 @@ "def autopost(): return Html(Div('Text.', hx_post=yoyo()))\n", "print(cli.get('/autopost').text)" ], - "id": "7c411a85a21ad08e" + "id": "bf550a863e622bb1" }, { "metadata": {}, @@ -2542,7 +2553,7 @@ "def autopost2(): return Html(Body(Div('Text.', cls='px-2', hx_post=show_host.to(a='b'))))\n", "print(cli.get('/autopost2').text)" ], - "id": "8c38b939291ab644" + "id": "5c264fec32f081e0" }, { "metadata": {}, @@ -2554,7 +2565,7 @@ "def autoget2(): return Html(Div('Text.', hx_get=show_host))\n", "print(cli.get('/autoget2').text)" ], - "id": "a77a1f47c56e36d9" + "id": "cb14ea89414940fb" }, { "metadata": {}, @@ -2566,7 +2577,7 @@ "def get(nm:str=''): return f\"Good day to you, {nm}!\"\n", "cli.get('/user/Alexis').text" ], - "id": "3c20651b84de0f59" + "id": "561f7d3538fc1228" }, { "metadata": {}, @@ -2578,7 +2589,7 @@ "def autolink(): return Html(Div('Text.', link=uri('gday', nm='Alexis')))\n", "print(cli.get('/autolink').text)" ], - "id": "2c788900a2ccdb73" + "id": "418113e5fa132dd5" }, { "metadata": {}, @@ -2591,7 +2602,7 @@ "\n", "cli.get('/link').text" ], - "id": "f657a1f73d5dfd2f" + "id": "3909c1dd3e3392c4" }, { "metadata": {}, @@ -2608,7 +2619,7 @@ "\n", "response = cli.get(\"/background\")" ], - "id": "8635c1055169bedf" + "id": "90716a3aea939978" }, { "metadata": {}, @@ -2616,7 +2627,7 @@ "outputs": [], "execution_count": null, "source": "test_eq(app.router.url_path_for('gday', nm='Jeremy'), '/user/Jeremy')", - "id": "b01c37683cd5749d" + "id": "1966de3a3b6b0b51" }, { "metadata": {}, @@ -2646,7 +2657,7 @@ "txt = cli.get('/xt3').text\n", "assert 'FastHTML page' not in txt and 'hi' in txt and '

there

' in txt" ], - "id": "985d18d4a0b94a29" + "id": "338a57122f4d7622" }, { "metadata": {}, @@ -2660,7 +2671,7 @@ "test_warns(lambda: rt('/oops')(_noanno))\n", "test_warns(lambda: rt('/barelist')(_bare))" ], - "id": "2ce18b792ac77487" + "id": "224151e95a080e42" }, { "metadata": {}, @@ -2672,7 +2683,7 @@ "test_warns(lambda: cli.get('/oops?nope=1'))\n", "test_warns(lambda: cli.get('/barelist?names=1'))" ], - "id": "26ea68a93689fd0b" + "id": "ed0f5226db71a55b" }, { "metadata": {}, @@ -2683,7 +2694,7 @@ "ModelName = str_enum('ModelName', \"alexnet\", \"resnet\", \"lenet\")\n", "fake_db = [{\"name\": \"Foo\"}, {\"name\": \"Bar\"}]" ], - "id": "e94e2e251db62443" + "id": "f8abfe73aa7e665b" }, { "metadata": {}, @@ -2694,7 +2705,7 @@ "@rt('/html/{idx}')\n", "async def get(idx:int): return Body(H4(f'Next is {idx+1}.'))" ], - "id": "32fa349b79d75e70" + "id": "c9be8b9a13c7b" }, { "metadata": {}, @@ -2720,7 +2731,7 @@ "@rt(\"/unionidxl/\")\n", "def get(idx:list[int] | None): return str(idx)" ], - "id": "a4b214dffb848f61" + "id": "c09b199ed001f5c7" }, { "metadata": {}, @@ -2741,7 +2752,7 @@ "test_r(cli, '/optidxl/?idx=1&idx=2', '[1, 2]')\n", "test_r(cli, '/unionidxl/?idx=1&idx=2', '[1, 2]')" ], - "id": "5496149d1a02c20d" + "id": "ec2f7f8a97792fd" }, { "metadata": {}, @@ -2758,7 +2769,7 @@ "def foo(path:str, a:int): return f'also got {path},{a}'\n", "cli.get('/static/sub/a.b.jpg').text" ], - "id": "855956c3bfb4adee" + "id": "806bd5c5b8214027" }, { "metadata": {}, @@ -2766,7 +2777,7 @@ "outputs": [], "execution_count": null, "source": "cli.get('/static/sub/a.b?a=1').text", - "id": "97b1292db472196b" + "id": "41ad4d0dae24e431" }, { "metadata": {}, @@ -2774,7 +2785,7 @@ "outputs": [], "execution_count": null, "source": "app.chk = 'foo'", - "id": "ea361055b7188aff" + "id": "270b73ac388beec3" }, { "metadata": {}, @@ -2809,7 +2820,7 @@ "@app.get(\"/app4\")\n", "def _(foo:FastHTML): return Redirect(\"http://example.org\")" ], - "id": "7f15062539128c48" + "id": "5bb28848fd83279f" }, { "metadata": {}, @@ -2826,7 +2837,7 @@ "test_r(cli, '/hxtest2', '1', headers={'HX-Request':'1'})\n", "test_r(cli, '/app' , 'foo')" ], - "id": "944594c4209fdc7c" + "id": "46d098bb8867c394" }, { "metadata": {}, @@ -2838,7 +2849,7 @@ "test_eq(r.text, 'foo')\n", "test_eq(r.headers['mykey'], 'myval')" ], - "id": "b4689d6ff7d4123a" + "id": "cf42935badd43f5f" }, { "metadata": {}, @@ -2849,7 +2860,7 @@ "r = cli.get('/app3')\n", "test_eq(r.headers['HX-Location'], 'http://example.org')" ], - "id": "295ae52452b974b6" + "id": "925cf36bab1b36bd" }, { "metadata": {}, @@ -2860,7 +2871,7 @@ "r = cli.get('/app4', follow_redirects=False)\n", "test_eq(r.status_code, 303)" ], - "id": "5dfa9fdf9be7c0ab" + "id": "57f7ee8411e7b167" }, { "metadata": {}, @@ -2871,7 +2882,7 @@ "r = cli.get('/app4', headers={'HX-Request':'1'})\n", "test_eq(r.headers['HX-Redirect'], 'http://example.org')" ], - "id": "c25ee2b4ae9af9db" + "id": "8dd137ec345034ec" }, { "metadata": {}, @@ -2886,7 +2897,7 @@ "assert re.search(r'\\s*

hi

\\s*', t)\n", "assert 'It worked!\" in response and \"

15, Lorem

\" in response" ], - "id": "f8c5a79a9e268cad" + "id": "ec3b771e001ee9c7" }, { "metadata": {}, @@ -3014,7 +3025,7 @@ "response = cli.post('/bodytext', headers={\"Content-Type\": \"application/json\"}, data=s).text\n", "test_eq(response, '{\"b\": \"Lorem\", \"a\": 15}')" ], - "id": "1c271ec1f072e066" + "id": "98e17f17ef0dc78a" }, { "metadata": {}, @@ -3022,7 +3033,7 @@ "outputs": [], "execution_count": null, "source": "files = [('files', ('file1.txt', b'content1')), ('files', ('file2.txt', b'content2'))]", - "id": "93a69784d0a2b6b3" + "id": "ec6e5345e542ab55" }, { "metadata": {}, @@ -3037,7 +3048,7 @@ "print(res.status_code)\n", "print(res.text)" ], - "id": "8f88c027dbebba62" + "id": "2c61b6a60b3540d6" }, { "metadata": {}, @@ -3049,7 +3060,7 @@ "test_eq(res.status_code, 200)\n", "test_eq(res.text, 'content1')" ], - "id": "a1705546441529ca" + "id": "7ec54f9bf1c48765" }, { "metadata": {}, @@ -3071,7 +3082,7 @@ "\n", "cli.get('/getsess').text" ], - "id": "ad0e269042b27e7e" + "id": "aad9b9ce36863a63" }, { "metadata": {}, @@ -3091,7 +3102,7 @@ "\n", "test_eq(cli.get('/getsess-all').text, '2')" ], - "id": "f5ca9e1ef115a62a" + "id": "34c2f446da12947a" }, { "metadata": {}, @@ -3104,7 +3115,7 @@ "\n", "with open('../../CHANGELOG.md', 'rb') as f: print(cli.post('/upload', files={'uf':f}, data={'msg':'Hello'}).text[:15])" ], - "id": "409b7720eb224b52" + "id": "c92b006916962f75" }, { "metadata": {}, @@ -3117,7 +3128,7 @@ " headers = {'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'POST', 'Access-Control-Allow-Headers': '*'}\n", " return Response(status_code=200, headers=headers)" ], - "id": "f343fe095bb6667" + "id": "ec51f25bd3652cd1" }, { "metadata": {}, @@ -3128,7 +3139,7 @@ "h = cli.options('/form-submit/2').headers\n", "test_eq(h['Access-Control-Allow-Methods'], 'POST')" ], - "id": "c079a9480076de20" + "id": "d460e6dbdb8dd934" }, { "metadata": {}, @@ -3136,7 +3147,7 @@ "outputs": [], "execution_count": null, "source": "from fasthtml.authmw import user_pwd_auth", - "id": "c3a0b4e98373614e" + "id": "3d7dbed27003480a" }, { "metadata": {}, @@ -3152,7 +3163,7 @@ "assert '
nope
' in txt\n", "assert '' in txt" ], - "id": "2f8b30794712e0c2" + "id": "864cf99f2c3ae7e4" }, { "metadata": {}, @@ -3168,7 +3179,7 @@ "assert 'Hello Uma, age 5' in cli.get('/uma/5').text\n", "assert '404 Not Found' in cli.get('/uma/five').text" ], - "id": "90ba5b8403a3879d" + "id": "ec071d4434f7b01e" }, { "metadata": {}, @@ -3185,7 +3196,7 @@ "test_eq(cli.get('/locked').text, 'not authenticated')\n", "test_eq(cli.get('/locked', auth=(\"testuser\",\"spycraft\")).text, 'Hello, testuser')" ], - "id": "cd1418adab7bc3b1" + "id": "f5690664c11111c3" }, { "metadata": {}, @@ -3202,13 +3213,13 @@ "test_eq(cli.get('/locked').text, 'not authenticated')\n", "test_eq(cli.get('/locked', auth=(\"testuser\",\"spycraft\")).text, 'Hello, testuser')" ], - "id": "3d6b883e14f63a74" + "id": "35906bc86879e702" }, { "metadata": {}, "cell_type": "markdown", "source": "Check that afterware like toasts are called correctly.", - "id": "504abfeb5c1f9a9c" + "id": "715da9a9f886acdb" }, { "metadata": {}, @@ -3216,7 +3227,7 @@ "outputs": [], "execution_count": null, "source": "from fasthtml.toaster import *", - "id": "bf8618699f50aed1" + "id": "e097e6f2f34810bc" }, { "metadata": {}, @@ -3258,13 +3269,13 @@ "r = cli.get('/')\n", "assert tm in r.text" ], - "id": "8d549d9a5c93d99d" + "id": "a1b6328777990e33" }, { "metadata": {}, "cell_type": "markdown", "source": "Here's a quick sanity check to confirm that toasts are rendered in the toast container correctly. See [issue](https://github.com/AnswerDotAI/fasthtml/issues/762).", - "id": "9fab408e2e6e686" + "id": "71feed8c8eec723c" }, { "metadata": {}, @@ -3272,7 +3283,7 @@ "outputs": [], "execution_count": null, "source": "assert 'id=\"fh-toast-container\"' in r.text", - "id": "4bd5e983e3d3af53" + "id": "37285b1359490d0a" }, { "metadata": {}, @@ -3289,7 +3300,7 @@ "with cli: test_eq(cli.get('/').text, 'True')\n", "test_eq(app._stopped, True)" ], - "id": "f5bd3ba8f7e070c1" + "id": "3911e2efa6eff2f7" }, { "metadata": {}, @@ -3307,13 +3318,13 @@ "\n", "with cli: test_eq(cli.get('/').text, 'fired')" ], - "id": "e1e0a2981bdd9bed" + "id": "31ea8e937c9f18cb" }, { "metadata": {}, "cell_type": "markdown", "source": "A route-level `before` can set session data, short-circuit with a response, or raise to block access:", - "id": "e186cdcbef7aa053" + "id": "913d1b3cb80c4d0c" }, { "metadata": {}, @@ -3335,13 +3346,13 @@ "test_eq(cli.get('/dashboard?user=guest').text, 'guest view')\n", "test_eq(cli.get('/dashboard?user=other').status_code, 403)" ], - "id": "375bfb6e0574c3b1" + "id": "42b7166381b2de31" }, { "metadata": {}, "cell_type": "markdown", "source": "Multiple `before` functions run in order, each receiving the injected request params:", - "id": "59fd36c5878e8631" + "id": "f827e72640085b2f" }, { "metadata": {}, @@ -3357,13 +3368,13 @@ "\n", "test_eq(cli.get('/multi').text, '1,2')" ], - "id": "1b6335c5da6b5da4" + "id": "63ab236a7e4c8b5e" }, { "metadata": {}, "cell_type": "markdown", "source": "A truthy return from any `before` becomes the response; remaining `before`s and the handler are skipped (return `None` to continue):", - "id": "b8218676a7553fae" + "id": "ecba79afd0c3b9e8" }, { "metadata": {}, @@ -3383,13 +3394,13 @@ "test_eq(cli.get('/chain').text, 'stop')\n", "test_eq(calls, ['first'])" ], - "id": "ff2355f5ac88a72d" + "id": "b834f3053cdaaff5" }, { "metadata": {}, "cell_type": "markdown", "source": "`cancel_on_disconnect` handlers keep their normal parameters; the handler is cancelled if the client disconnects, or after `timeout` seconds if given:", - "id": "80260448c4476ee0" + "id": "86b74f597dc5d2e9" }, { "metadata": {}, @@ -3405,7 +3416,7 @@ "\n", "test_eq(cli.get('/cq?q=x').text, 'got x')" ], - "id": "b2148b69758de6f" + "id": "e64d3e485aa691fd" }, { "metadata": {}, @@ -3421,13 +3432,13 @@ "\n", "test_fail(lambda: cli.get('/sleepy'))" ], - "id": "ac7273a868548b84" + "id": "d11b1608d51eb867" }, { "metadata": {}, "cell_type": "markdown", "source": "On disconnect the handler is cancelled and an empty response returned, which the server discards since the client is gone. Here we simulate the ASGI `http.disconnect` message directly:", - "id": "5819b50f4728bc55" + "id": "78bcb538beffc3c1" }, { "metadata": {}, @@ -3452,13 +3463,13 @@ "test_eq(run_sync(_t()).status_code, 204)\n", "test_eq(cancelled, [True])" ], - "id": "6dd453e187a01b13" + "id": "d9b6647ef0b1c120" }, { "metadata": {}, "cell_type": "markdown", "source": "## APIRouter", - "id": "cb43430858dcac10" + "id": "a3ef3aafeed1c543" }, { "metadata": {}, @@ -3477,7 +3488,7 @@ " except KeyError: raise AttributeError(f\"No route named {name} found in route functions\")\n", " def __dir__(self): return list(self._funcs.keys())" ], - "id": "6d212239ee4b3ebb" + "id": "8d1ad3aa405f8952" }, { "metadata": {}, @@ -3525,7 +3536,7 @@ " def f(func=noop): return self.wss.append((func, f\"{self.prefix}{path}\", conn, disconn, name, middleware))\n", " return f" ], - "id": "c069560553ea4e31" + "id": "93fc46fe69d90aa2" }, { "metadata": {}, @@ -3533,7 +3544,7 @@ "outputs": [], "execution_count": null, "source": "ar = APIRouter()", - "id": "7053f84ef1ee93f6" + "id": "b5410d5e8e309c99" }, { "metadata": {}, @@ -3563,7 +3574,7 @@ "@ar.ws(\"/ws\")\n", "def ws(self, msg:str): return f\"Message text was: {msg}\"" ], - "id": "c0ff4dc1dfe83148" + "id": "2bf8cf65a3dd1945" }, { "metadata": {}, @@ -3574,7 +3585,7 @@ "app,cli,_ = get_cli(FastHTML())\n", "ar.to_app(app)" ], - "id": "d78e389d3610d965" + "id": "8b3f8ed2df1bde26" }, { "metadata": {}, @@ -3592,7 +3603,7 @@ "# ensure any route functions named using an HTTPMethod are not discoverable via `rt_funcs`\n", "assert \"get\" not in ar.rt_funcs._funcs.keys()" ], - "id": "c8ebe7cfdc63718" + "id": "73718966d4787400" }, { "metadata": {}, @@ -3613,7 +3624,7 @@ "test_eq(cli.delete('/class-cards/abc').text, 'delete abc')\n", "test_eq(CardMethods.to(id='xyz'), '/class-cards/xyz')" ], - "id": "6a60b59b118846a6" + "id": "5acb58e120365823" }, { "metadata": {}, @@ -3626,7 +3637,7 @@ " data = ws.receive_text()\n", " assert data == 'Message text was: Hi!'" ], - "id": "b8e12162ea3e310c" + "id": "5ac26b06271b614" }, { "metadata": {}, @@ -3634,7 +3645,7 @@ "outputs": [], "execution_count": null, "source": "ar2 = APIRouter(\"/products\")", - "id": "34dc5eb7b3152b1c" + "id": "26ba77d9d7360fe8" }, { "metadata": {}, @@ -3662,7 +3673,7 @@ "@ar2.ws(\"/ws\")\n", "def ws(self, msg:str): return f\"Message text was: {msg}\"" ], - "id": "5ea40de23ef540fd" + "id": "8be654b68b7e4fd6" }, { "metadata": {}, @@ -3673,7 +3684,7 @@ "app,cli,_ = get_cli(FastHTML())\n", "ar2.to_app(app)" ], - "id": "50efe1782d71c63d" + "id": "71d836196c32426d" }, { "metadata": {}, @@ -3690,7 +3701,7 @@ "with ExceptionExpected(): ar2.rt_funcs.blah()\n", "assert \"get\" not in ar2.rt_funcs._funcs.keys()" ], - "id": "5e76acbce9b744e9" + "id": "b4acf9b9badda242" }, { "metadata": {}, @@ -3709,7 +3720,7 @@ "test_eq(cli.get('/products/products?id=7').text, 'product 7')\n", "test_eq(Products.to(id=7), '/products/products?id=7')" ], - "id": "74d0e896f59faa34" + "id": "1a999d4fe38dc396" }, { "metadata": {}, @@ -3722,7 +3733,7 @@ " data = ws.receive_text()\n", " assert data == 'Message text was: Hi!'" ], - "id": "3f575fb7222c54cd" + "id": "a3201869573175c1" }, { "metadata": {}, @@ -3733,7 +3744,7 @@ "#| export\n", "for o in all_meths: setattr(APIRouter, o, partialmethod(APIRouter.__call__, methods=o))" ], - "id": "6d6695412ac8dccd" + "id": "1859d1c226783abe" }, { "metadata": {}, @@ -3755,13 +3766,13 @@ "@ar2.post(\"/post2\")\n", "def _(): return 'Postal'" ], - "id": "2fd1f4a196f51927" + "id": "3f2e9dfaf07906ad" }, { "metadata": {}, "cell_type": "markdown", "source": "## Extras", - "id": "d14d79e176792cd8" + "id": "cefabdfd3804ce65" }, { "metadata": {}, @@ -3769,7 +3780,7 @@ "outputs": [], "execution_count": null, "source": "app,cli,rt = get_cli(FastHTML(secret_key='soopersecret'))", - "id": "710d59fe07e76a4e" + "id": "f4f134d385ba979c" }, { "metadata": {}, @@ -3794,7 +3805,7 @@ " cookie_val = cookie.output(header=\"\").strip()\n", " return HttpHeader(\"set-cookie\", cookie_val)" ], - "id": "4b8cabb822ba5c06" + "id": "8db47f8de086a404" }, { "metadata": {}, @@ -3812,7 +3823,7 @@ "time.sleep(0.01)\n", "cli.get('/getcookie').text" ], - "id": "9020523bd7e93f" + "id": "b83427dfe5a39ae8" }, { "metadata": {}, @@ -3826,7 +3837,7 @@ " cls = get_class(f'{m}Conv', sup=StringConvertor, regex=s)\n", " register_url_convertor(m, cls())" ], - "id": "5cdac562bf659976" + "id": "d18e6ecc94583abc" }, { "metadata": {}, @@ -3846,7 +3857,7 @@ " @self.get(f\"{prefix}{{fname:path}}.{{ext:{exts}}}\")\n", " async def get(fname:str, ext:str): return FileResponse(f'{static_path}/{fname}.{ext}')" ], - "id": "f39ce8a9974eb311" + "id": "88b7340a78a5e97c" }, { "metadata": {}, @@ -3861,7 +3872,7 @@ "\n", "test_r(cli, '/static/foo/jph.me.ico', 'Getting jph.me.ico from /foo/')" ], - "id": "652c879213bfb742" + "id": "dd357f05f363eddb" }, { "metadata": {}, @@ -3872,7 +3883,7 @@ "app.static_route_exts()\n", "assert 'These are the source notebooks for FastHTML' in cli.get('/README.txt').text" ], - "id": "14ac1dcb187e9ded" + "id": "7e6039c9c6cc9e" }, { "metadata": {}, @@ -3887,7 +3898,7 @@ " @self.get(f\"{prefix}{{fname:path}}{ext}\")\n", " async def get(fname:str): return FileResponse(f'{static_path}/{fname}{ext}')" ], - "id": "f3b305241d618c09" + "id": "4433cd8119244424" }, { "metadata": {}, @@ -3898,7 +3909,7 @@ "app.static_route('.md', static_path='../..')\n", "assert 'THIS FILE WAS AUTOGENERATED' in cli.get('/README.md').text" ], - "id": "a71a0eb39efe8d5c" + "id": "2f661b66f3e94173" }, { "metadata": {}, @@ -3914,7 +3925,7 @@ " resp.headers.setdefault(\"Cache-Control\", \"no-cache\")\n", " return resp" ], - "id": "dfc415e286f4b8" + "id": "7dd76a7c38bf4ec0" }, { "metadata": {}, @@ -3930,13 +3941,13 @@ " resp.headers.setdefault(\"Cache-Control\", \"public, max-age=31536000, immutable\")\n", " return resp" ], - "id": "23fae82950b80317" + "id": "341dff8d4f8feb92" }, { "metadata": {}, "cell_type": "markdown", "source": "These two classes are the poles of static-file caching. `StaticNoCache` makes the browser revalidate on every use: always fresh at the cost of a conditional request each time, right for files that change under a stable URL (and for dev, where you want edits visible on reload). `StaticImmutable` promises the URL's content will never change, so the browser may cache it forever with no requests at all: only safe when a changed file gets a changed URL, which is what `vurl` or a bundler's content-hashed filenames provide.", - "id": "58f59f41ea0160e0" + "id": "70c4f465f1a1e4d9" }, { "metadata": {}, @@ -3951,7 +3962,7 @@ "test_eq(stat_cli.get('/nc/app.css').headers['cache-control'], 'no-cache')\n", "test_eq(stat_cli.get('/imm/app.css').headers['cache-control'], 'public, max-age=31536000, immutable')" ], - "id": "d107a4932dcdd8a" + "id": "78397e0f041db120" }, { "metadata": {}, @@ -3970,13 +3981,13 @@ " q = f'{u.query}&' if u.query else ''\n", " return urlunsplit(u._replace(query=f'{q}v={_vhash(p)}'))\n" ], - "id": "17e13907ee30fc50" + "id": "91e627079c83160d" }, { "metadata": {}, "cell_type": "markdown", "source": "Browsers use the URL as the cache key, so a URL that changes whenever the file's contents change can be cached forever: serve the mount with `StaticImmutable` and the asset costs no requests at all until it is next edited. This is the query-param version of the content-hashed filenames that asset pipelines and bundlers produce, without the build step. The hash is cached via `flexicache` with `mtime_policy`, so a call costs one `stat` and the file is only re-read after it changes. The param is inert under `no-cache` serving, so the same links work in dev with `StaticNoCache`, where the file is rechecked on each reload.", - "id": "b72b1bfca5946f5b" + "id": "bc9f863ad8101d60" }, { "metadata": {}, @@ -3996,7 +4007,7 @@ "os.utime(tmp/'a.css', (time.time()+1,)*2)\n", "assert vurl('a.css', tmp) != u" ], - "id": "8215a537819de8bd" + "id": "35c4396c812bdbbb" }, { "metadata": {}, @@ -4008,7 +4019,7 @@ "from functools import wraps\n", "from inspect import signature, isawaitable" ], - "id": "1a6cbfc05998c35d" + "id": "e77d8aa644feefcd" }, { "metadata": {}, @@ -4027,7 +4038,7 @@ " f.__annotations__[name] = typ\n", " return f" ], - "id": "66cc946f0f8a8894" + "id": "97d0447b3fe8d090" }, { "metadata": {}, @@ -4057,19 +4068,19 @@ " add_sig_param(_inner, k, anno, default=p.default)\n", " return _inner" ], - "id": "ffee8e07c9b7665d" + "id": "d9d0b14c50a4ee20" }, { "metadata": {}, "cell_type": "markdown", "source": "`into` is a decorator that composes two functions: the decorated route function and an outer \"wrapper\" function (like a layout). The route's return value is passed as positional args to the wrapper. Any keyword parameters listed in `params` are added to the route's signature, so they become available as query/form parameters. This lets you write simple routes that return just their content, while the layout and its parameters are handled automatically.", - "id": "1d7a5679528c39d" + "id": "170d28cff6e4799a" }, { "metadata": {}, "cell_type": "markdown", "source": "Here `hello` returns a single `P` tag, but `into(my_layout)` passes it into `my_layout`, which wraps it in a `Titled`. The `title` parameter is injected into `hello`'s signature so it can be set via query params.", - "id": "fa58fb4fd02c2db0" + "id": "da98f752664d3c67" }, { "metadata": {}, @@ -4085,13 +4096,13 @@ "@into(my_layout)\n", "def hello(name:str='World'): return P(f'Hello, {name}!')" ], - "id": "3e1fe925afb7969" + "id": "ef603fee8f8e74f9" }, { "metadata": {}, "cell_type": "markdown", "source": "With no query params, `name` defaults to `'World'` and `title` defaults to `'Default'` (from `my_layout`'s own default), giving us a page titled \"Default\" containing \"Hello, World!\".", - "id": "6d3457d3d02d70e" + "id": "c9e190baca5d582c" }, { "metadata": {}, @@ -4103,13 +4114,13 @@ "assert 'Default' in r.text\n", "assert '

Hello, World!

' in r.text" ], - "id": "2e12f2654d9f9548" + "id": "af10b39dcbaf6fcf" }, { "metadata": {}, "cell_type": "markdown", "source": "Here, both `name` and `title` are provided as query params. `name='Jeremy'` is handled by `hello` directly, while `title='Greetings'` is the injected param that gets forwarded to `my_layout`.", - "id": "d16aabdb9df9fc0d" + "id": "dc4f32eee6a84a4" }, { "metadata": {}, @@ -4121,7 +4132,7 @@ "assert 'Greetings' in r.text\n", "assert '

Hello, Jeremy!

' in r.text" ], - "id": "f813fe19102b7fc7" + "id": "9b9ac10381a145ae" }, { "metadata": {}, @@ -4137,7 +4148,7 @@ " await self._app(scope, receive, send)\n", " " ], - "id": "621de4f72f855409" + "id": "7a5ebb738f694d75" }, { "metadata": {}, @@ -4160,7 +4171,7 @@ " headers = {**(self.headers or {}), **httphdrs}\n", " return self.cls(cts, status_code=self.status_code, headers=headers, media_type=self.media_type, background=tasks)" ], - "id": "a19aeb513a26811d" + "id": "41b3a970fb0d5b7c" }, { "metadata": {}, @@ -4180,13 +4191,13 @@ "txt = r.text\n", "assert 'Foo' in txt and '

bar

' in txt and '' in txt" ], - "id": "97242b82a893fb30" + "id": "4bd5d1f492918b6a" }, { "metadata": {}, "cell_type": "markdown", "source": "Test on a single background task:", - "id": "cbc9c706e4bf24c6" + "id": "6df76d2a9608cbdc" }, { "metadata": {}, @@ -4207,13 +4218,13 @@ "test_eq(r.status_code, 200)\n", "\n" ], - "id": "dcd54920e1965347" + "id": "d08eb5f58af30580" }, { "metadata": {}, "cell_type": "markdown", "source": "Test multiple background tasks:", - "id": "9400f23cc2ac6adc" + "id": "99c9fd088ff2c315" }, { "metadata": {}, @@ -4227,7 +4238,7 @@ " time.sleep(amount)\n", " print(f'Slept for {amount}s') " ], - "id": "20ea3030ace925f8" + "id": "a5502eff873e0492" }, { "metadata": {}, @@ -4244,7 +4255,7 @@ "r = cli.get('/backgrounds')\n", "test_eq(r.status_code, 200)" ], - "id": "eab10bb45ede6f25" + "id": "1536be70e3244b35" }, { "metadata": {}, @@ -4260,7 +4271,7 @@ "r = cli.get('/backgrounds2')\n", "test_eq(r.status_code, 200)" ], - "id": "67a11c47e760e088" + "id": "d4bca91cd874fc15" }, { "metadata": {}, @@ -4277,7 +4288,7 @@ "test_eq(r.status_code, 200)\n", "r.json()" ], - "id": "57f456b964a6c2b7" + "id": "e20e7c963bf0e8d3" }, { "metadata": {}, @@ -4292,7 +4303,7 @@ " res = b64encode(id4.bytes)\n", " return '_' + res.decode().rstrip('=').translate(str.maketrans('+/', '_-'))" ], - "id": "335006dfb096cead" + "id": "eabef5efb84fbbce" }, { "metadata": {}, @@ -4306,7 +4317,7 @@ " if not getattr(s, 'id', None): s.id = unqid()\n", " for c in s.children: _add_ids(c)" ], - "id": "637735f394562e3a" + "id": "7b02ac1afad917b7" }, { "metadata": {}, @@ -4326,7 +4337,7 @@ " app._send = send\n", " return send" ], - "id": "7740b43745222106" + "id": "3214911e487f8536" }, { "metadata": {}, @@ -4344,7 +4355,7 @@ " @self.route(devtools_loc)\n", " def devtools(): return dict(workspace=dict(root=str(path), uuid=uuid))" ], - "id": "c31e7509d1ca707" + "id": "9b073cb96670c884" }, { "metadata": {}, @@ -4364,7 +4375,7 @@ " client.cookies.update({self.session_cookie: data.decode()})\n", " return client" ], - "id": "96cfdb7d4d31f050" + "id": "d9fc5093f40be209" }, { "metadata": {}, @@ -4380,7 +4391,7 @@ " unsigned = itsdangerous.TimestampSigner(self.secret_key).unsign(cookie, max_age=None)\n", " return loads(b64decode(unsigned).decode())" ], - "id": "2d51142bf081806d" + "id": "da949a3f6dd16b6c" }, { "metadata": {}, @@ -4403,7 +4414,7 @@ "\n", " return FastHTMLTestClient(self, cookies=self.get_client(**kw).cookies)" ], - "id": "6636f33a9b96f503" + "id": "a631620ade78cb51" }, { "metadata": {}, @@ -4414,13 +4425,13 @@ "cli = app.get_testclient(auth='user1')\n", "test_eq(cli.session['auth'], 'user1')" ], - "id": "8141e15a8ce24b5f" + "id": "9a572b597b4142d6" }, { "metadata": {}, "cell_type": "markdown", "source": "## Export -", - "id": "5551a408cd475b7" + "id": "87aff436308386ab" }, { "metadata": {}, @@ -4432,7 +4443,7 @@ "import nbdev\n", "nbdev.nbdev_export()" ], - "id": "a48bde6e158344c0" + "id": "8e4a52eca26ad422" } ], "metadata": { From 2baf89574b010421d32acd06734feeb30dd8b55b Mon Sep 17 00:00:00 2001 From: Renato Gomes Damas Date: Tue, 20 Oct 2026 17:06:04 -0300 Subject: [PATCH 12/14] refactor: update code cell structure --- nbs/api/00_core.ipynb | 576 +++++++++++++++++++++--------------------- 1 file changed, 288 insertions(+), 288 deletions(-) diff --git a/nbs/api/00_core.ipynb b/nbs/api/00_core.ipynb index b1efc44d..b0c3165e 100644 --- a/nbs/api/00_core.ipynb +++ b/nbs/api/00_core.ipynb @@ -6,7 +6,7 @@ "outputs": [], "execution_count": null, "source": "#| default_exp core", - "id": "bc698490f70ad760" + "id": "abd0715bf7152ac0" }, { "metadata": {}, @@ -15,7 +15,7 @@ "# Core\n", "> The `FastHTML` subclass of `Starlette`." ], - "id": "7cfa9456b28add27" + "id": "bca716270de06332" }, { "metadata": {}, @@ -62,19 +62,19 @@ "\n", "See the [Handling Handlers tutorial](https://www.fastht.ml/docs/ref/handlers.html.md) for worked examples of the above." ], - "id": "4a5c40cbd6b96a37" + "id": "e0208107ef170c3a" }, { "metadata": {}, "cell_type": "markdown", "source": "This is the source code to fasthtml. You won't need to read this unless you want to understand how things are built behind the scenes, or need full details of a particular API. The notebook is converted to the Python module [fasthtml/core.py](https://github.com/AnswerDotAI/fasthtml/blob/main/fasthtml/core.py) using [nbdev](https://nbdev.fast.ai/).", - "id": "a70d5d3182ca303b" + "id": "b6fcb0a721031c64" }, { "metadata": {}, "cell_type": "markdown", "source": "## Imports and utils", - "id": "687079de57a42a34" + "id": "b8c87c3bdf8337e1" }, { "metadata": {}, @@ -110,7 +110,7 @@ "from fasthtml.starlette import *\n", "from python_multipart.exceptions import MultipartParseError" ], - "id": "74eb565a6ca22027" + "id": "d60896b1be9a376b" }, { "metadata": {}, @@ -131,7 +131,7 @@ "from fastcore.net import run_sync\n", "from starlette.datastructures import UploadFile" ], - "id": "908ef33d5b949d61" + "id": "aba058a56d848e71" }, { "metadata": {}, @@ -144,13 +144,13 @@ "\n", "empty = Parameter.empty" ], - "id": "c2e8bf6eec8515ea" + "id": "109f63591961b4b7" }, { "metadata": {}, "cell_type": "markdown", "source": "We write source code _first_, and then tests come _after_. The tests serve as both a means to confirm that the code works and also serves as working examples. The first exported function, `parsed_date`, is an example of this pattern.", - "id": "a48905ec29e84b05" + "id": "21a75d01b7bdb039" }, { "metadata": {}, @@ -163,7 +163,7 @@ " \"Convert `s` to a datetime\"\n", " return dtparse.parse(s)" ], - "id": "3db9e4e5a4a60f47" + "id": "ef535f00a2a89f4b" }, { "metadata": {}, @@ -171,7 +171,7 @@ "outputs": [], "execution_count": null, "source": "parsed_date('2pm')", - "id": "f0d0ab89fcf93351" + "id": "bc2cb214de4fcf1d" }, { "metadata": {}, @@ -179,7 +179,7 @@ "outputs": [], "execution_count": null, "source": "isinstance(date.fromtimestamp(0), date)", - "id": "d772a5c1a3e07e1b" + "id": "a26820d3b1c9070b" }, { "metadata": {}, @@ -193,7 +193,7 @@ " s = snake2camel(s)\n", " return camel2words(s, '-')" ], - "id": "cbb1cc44abb83dea" + "id": "5fb1e4617a486fa5" }, { "metadata": {}, @@ -201,7 +201,7 @@ "outputs": [], "execution_count": null, "source": "snake2hyphens(\"snake_case\")", - "id": "45e928d3bf8a0127" + "id": "19519192103191cb" }, { "metadata": {}, @@ -234,7 +234,7 @@ " res = {k:h.get(v.lower(), None) for k,v in htmx_hdrs.items()}\n", " return HtmxHeaders(**res)" ], - "id": "912545966705bf8b" + "id": "2be18465e895ee76" }, { "metadata": {}, @@ -249,7 +249,7 @@ " async def receive(): return dict(type=\"http.request\", body=b\"\", more_body=False)\n", " return Request(scope, receive)" ], - "id": "cdf830e0fbb7a8e5" + "id": "55bd364a9292ab0a" }, { "metadata": {}, @@ -260,7 +260,7 @@ "h = test_request(headers=Headers({'HX-Request':'1'}))\n", "_get_htmx(h.headers)" ], - "id": "f767c1bb72d9d113" + "id": "6992101105b572e2" }, { "metadata": {}, @@ -271,13 +271,13 @@ "#| export\n", "def _mk_list(t, v): return [t(o) for o in listify(v)]" ], - "id": "63601ad8dd759b99" + "id": "dcb0d4d0e48ecdb0" }, { "metadata": {}, "cell_type": "markdown", "source": "## Request and response", - "id": "31e875a70b7d36a5" + "id": "7826b57de89c3067" }, { "metadata": {}, @@ -288,7 +288,7 @@ "#| export\n", "fh_cfg = AttrDict(indent=True)" ], - "id": "cbc801d046d7d084" + "id": "43fff0ca21fc8aee" }, { "metadata": {}, @@ -304,7 +304,7 @@ " if anno is empty and arg.lower() not in _special_names and not any(s.startswith(arg.lower()) for s in ('request','session')): return f\"`{arg}` has no type annotation and is not a recognised special name, so is ignored.\"\n", " if isinstance(anno, type) and not get_origin(anno) and issubclass(anno, (list, tuple)) and not _is_body(anno): return f\"`{arg}` uses bare `{anno.__name__}` annotation, so is ignored (use e.g. `{anno.__name__}[str]` instead).\"" ], - "id": "a226ee3cccb2519e" + "id": "305a6017196e36c3" }, { "metadata": {}, @@ -325,7 +325,7 @@ " if not isinstance(o, (str,list,tuple)): return o\n", " return res(o[-1]) if isinstance(o,(list,tuple)) else res(o)" ], - "id": "9ce04062c728e12d" + "id": "8209bd0bd8a2c826" }, { "metadata": {}, @@ -346,7 +346,7 @@ "test_eq(_fix_anno(list[str], []), [])\n", "test_eq(_fix_anno(Optional[list[str]], '1'), ['1'])" ], - "id": "ede3b755b5964d1c" + "id": "2143de2a74a16ce5" }, { "metadata": {}, @@ -364,7 +364,7 @@ " if not anno: return v\n", " return _fix_anno(anno, v)" ], - "id": "e9cff1c16a6133bf" + "id": "7b2b72d8228d8f14" }, { "metadata": {}, @@ -377,7 +377,7 @@ "test_eq(_form_arg('l', \"1\", d), [1])\n", "test_eq(_form_arg('l', [\"1\",\"2\"], d), [1,2])" ], - "id": "8fd54d1e73b50c65" + "id": "69ac6def9a2e62c2" }, { "metadata": {}, @@ -391,7 +391,7 @@ " \"A response header as a k,v pair\"\n", " k:str;v:str" ], - "id": "ccae4a3e3396de7c" + "id": "b01823074c702f33" }, { "metadata": {}, @@ -405,7 +405,7 @@ "htmx_resps = dict(location=None, push_url=None, redirect=None, refresh=None, replace_url=None,\n", " reswap=None, retarget=None, reselect=None, trigger=None, trigger_after_settle=None, trigger_after_swap=None)" ], - "id": "475fcdfb7f60b95f" + "id": "564d73a5396b8e8" }, { "metadata": {}, @@ -413,7 +413,7 @@ "outputs": [], "execution_count": null, "source": "_to_htmx_header('trigger_after_settle')", - "id": "80392b12e1020f0b" + "id": "c8c89531103e4c60" }, { "metadata": {}, @@ -428,7 +428,7 @@ " res = tuple(HttpHeader(_to_htmx_header(k), v) for k,v in kwargs.items())\n", " return res[0] if len(res)==1 else res" ], - "id": "862adead1ff6fd91" + "id": "be6f8e38e13cfef4" }, { "metadata": {}, @@ -436,7 +436,7 @@ "outputs": [], "execution_count": null, "source": "HtmxResponseHeaders(trigger_after_settle='hi')", - "id": "9cf582da2f77eb69" + "id": "f6b9835d1571f588" }, { "metadata": {}, @@ -450,7 +450,7 @@ " if is_namedtuple(anno): return {o:str for o in anno._fields}\n", " return get_annotations(anno)" ], - "id": "a31232134dbe2ac" + "id": "10208f86a5c75153" }, { "metadata": {}, @@ -462,7 +462,7 @@ "class Foo: a:int; b:str\n", "_annotations(Foo)" ], - "id": "717938adccebe4f3" + "id": "555a8762a6dae6c7" }, { "metadata": {}, @@ -473,7 +473,7 @@ "Point = namedtuple('Point', ['x', 'y'])\n", "_annotations(Point)" ], - "id": "c49e5997904e333d" + "id": "f01ad1b910e68295" }, { "metadata": {}, @@ -484,7 +484,7 @@ "#| export\n", "def _is_body(anno): return issubclass(anno, (dict,ns)) or hasattr(anno,'__from_request__') or _annotations(anno)" ], - "id": "acf8e46c0b78a844" + "id": "3309bcdace4b0ee0" }, { "metadata": {}, @@ -500,7 +500,7 @@ " o = form.getlist(k)\n", " return o[0] if len(o) == 1 else o if o else None" ], - "id": "c47ddb9dca284510" + "id": "559151c1542e7b2c" }, { "metadata": {}, @@ -514,7 +514,7 @@ " if isinstance(form, dict): return form\n", " return {k: _formitem(form, k) for k in form}" ], - "id": "30a9fdb45d78cc71" + "id": "28c6f85adea7b96" }, { "metadata": {}, @@ -528,7 +528,7 @@ "test_eq(res['a'], [1,2])\n", "test_eq(res['b'], 0)" ], - "id": "1620a03b5b53c9ae" + "id": "2101f06572504ca7" }, { "metadata": {}, @@ -539,7 +539,7 @@ "#| export\n", "DEF_MAXPART = 100*1024*1024" ], - "id": "f1b4827ca0fe2157" + "id": "6119a9f086e5855" }, { "metadata": {}, @@ -566,13 +566,13 @@ " return res\n", " return await req.form(max_part_size=maxpart)" ], - "id": "1054d6149d8720ec" + "id": "b7a84fdc1e959dea" }, { "metadata": {}, "cell_type": "markdown", "source": "Use the special `__from_request__` class method for custom creation:", - "id": "2280bfd557b15769" + "id": "ec4b6bec4e8e794e" }, { "metadata": {}, @@ -586,7 +586,7 @@ " @classmethod\n", " def __from_request__(cls, data, req): return cls(data)" ], - "id": "551de704c7ecce25" + "id": "dc9b6f86c7944766" }, { "metadata": {}, @@ -600,7 +600,7 @@ "async def mock_form(**kwargs): return FormData({'a':1})\n", "req.form = mock_form" ], - "id": "2d97d6131b208778" + "id": "b8b66eac349389ef" }, { "metadata": {}, @@ -624,7 +624,7 @@ " cargs = {k: _form_arg(k, v, d) for k, v in data.items() if not d or k in d}\n", " return anno(**cargs)" ], - "id": "92dfc839766cc4a6" + "id": "681bd327beec6e72" }, { "metadata": {}, @@ -641,13 +641,13 @@ " def __call__(self, norm=None, **kw): return kw if self.isapi else norm\n", " def __bool__(self): return bool(self.isapi)" ], - "id": "fed371a8d4196a6e" + "id": "da86134ea3f91a3" }, { "metadata": {}, "cell_type": "markdown", "source": "Routes often need to return different responses depending on whether the request comes from a browser or an API client. The `api:ApiReturn` parameter handles this automatically — add it to any route signature and call it with two arguments: the API response and the browser response. If the request's `Accept` header is `application/json` then a dict of the kwargs is returned, otherwise, the first value is returned. For example, `return api(Redirect('/records'), id=record.id)` returns {'id':id} for API callers and a redirect for the browser. This keeps your route logic in one place instead of splitting it across separate endpoints.", - "id": "bf11cb6047e4bbcc" + "id": "29ea7f7ef01624e0" }, { "metadata": {}, @@ -663,7 +663,7 @@ " res = json.dumps(content, ensure_ascii=False, allow_nan=False, indent=None, separators=(\",\",\":\"), default=_default)\n", " return res.encode(\"utf-8\")\n" ], - "id": "53fde9431c4751d9" + "id": "745df49205bec54d" }, { "metadata": {}, @@ -684,7 +684,7 @@ "response = client.post('/', data=d)\n", "print(response.json())" ], - "id": "42c96871a0ed3570" + "id": "d651326e47868a29" }, { "metadata": {}, @@ -701,13 +701,13 @@ "res = client.post('/', json={'a':1}) # non-empty json still parses (behavior preserved)\n", "test_eq(res.json(), {'a':1})" ], - "id": "e28834e8078136ba" + "id": "4a4add89b5f4582a" }, { "metadata": {}, "cell_type": "markdown", "source": "A malformed multipart body (here the opening boundary isn't followed by CRLF) is the client's error, so `parse_form` answers 400 rather than letting the parser's exception surface as a 500:", - "id": "ae77b32f318ad7c2" + "id": "f0aaf06139498d27" }, { "metadata": {}, @@ -720,13 +720,13 @@ "test_eq(res.status_code, 400)\n", "res.text" ], - "id": "ba7a4c7ff2044fba" + "id": "c3c8f64bd923df80" }, { "metadata": {}, "cell_type": "markdown", "source": "A JSON body that does not decode, or decodes to something other than an object (an array, say), cannot supply route parameters, so it is refused with 400 rather than failing inside the form conversion:", - "id": "4b4c9ac6bb612971" + "id": "811f769f640298cc" }, { "metadata": {}, @@ -740,7 +740,7 @@ "test_eq(res.status_code, 400)\n", "res.text" ], - "id": "7f41ac48f4bd638" + "id": "11cb9db4b4adb623" }, { "metadata": {}, @@ -752,7 +752,7 @@ "client = TestClient(Starlette(routes=[Route('/', f, methods=['GET'])]))\n", "client.get('/?x=1&x=2').text" ], - "id": "9764bf75c1614912" + "id": "28ad1a98e6242bd" }, { "metadata": {}, @@ -820,7 +820,7 @@ " if isinstance(conn, Request): raise HTTPException(404, f\"{conn.url.path}: {e}\") from None\n", " raise" ], - "id": "e40a106c3f3f85fc" + "id": "76fd36997784bcc1" }, { "metadata": {}, @@ -831,7 +831,7 @@ "data = form2dict(await parse_form(req))\n", "await _from_body(req, p, data)" ], - "id": "92acee97a091aaa5" + "id": "7238bfa41ddecf3a" }, { "metadata": {}, @@ -844,7 +844,7 @@ " if conn.query_params: data |= dict(conn.query_params)\n", " return {arg:await _find_p(conn, data, hdrs, arg, p) for arg,p in params.items()}" ], - "id": "bf313685869a8006" + "id": "9fc8463265ad00e" }, { "metadata": {}, @@ -855,7 +855,7 @@ "data = form2dict(await parse_form(req))\n", "await _from_body(req, p, data)" ], - "id": "a32b68e1d3bc55b0" + "id": "d391f205f3d13615" }, { "metadata": {}, @@ -868,7 +868,7 @@ " data = form2dict(await parse_form(req))\n", " return await _find_ps(req, data, req.headers, params)" ], - "id": "b419de64cde702c1" + "id": "2cf24e42249b1531" }, { "metadata": {}, @@ -888,7 +888,7 @@ "test_eq(r.status_code, 200)\n", "print(r.text)" ], - "id": "1c872b17d28ab528" + "id": "c37802ba27f517fb" }, { "metadata": {}, @@ -906,7 +906,7 @@ "response = client.post('/?a=1', data=d)\n", "print(response.text)" ], - "id": "4f9212b9a87ad40f" + "id": "7c0d0a599755e4ef" }, { "metadata": {}, @@ -924,7 +924,7 @@ "response = client.post('/?a=1', data=d)\n", "print(response.text)" ], - "id": "bdad60519a7d7b2e" + "id": "ce987784ddbf635b" }, { "metadata": {}, @@ -946,19 +946,19 @@ "client = TestClient(Starlette(routes=[Route('/', f, methods=['POST'])]))\n", "client.post('/', headers={'Accept': 'application/json'}).text" ], - "id": "b5767c849a371a0e" + "id": "e2a191995d5e49c5" }, { "metadata": {}, "cell_type": "markdown", "source": "**Missing Request Params**", - "id": "db437a1989241169" + "id": "f306e1884f97945a" }, { "metadata": {}, "cell_type": "markdown", "source": "If a request param has a default value (e.g. `a:str=''`), the request is valid even if the user doesn't include the param in their request.", - "id": "de4ad9e40e66bfb7" + "id": "34730ee3ccdb005a" }, { "metadata": {}, @@ -976,13 +976,13 @@ "response = client.post('/', json={}) # no param in request\n", "print(response.text)" ], - "id": "55c862659aadd36c" + "id": "e214b6fdae0d2aab" }, { "metadata": {}, "cell_type": "markdown", "source": "If we remove the default value and re-run the request, we should get the following error `Missing required field: a`.", - "id": "308deaafd80faab3" + "id": "73ef231f8373b915" }, { "metadata": {}, @@ -1000,7 +1000,7 @@ "response = client.post('/', json={}) # no param in request\n", "print(response.text)" ], - "id": "659f5f100851b8bf" + "id": "a963b3c64f47a9c7" }, { "metadata": {}, @@ -1018,7 +1018,7 @@ " else: result.append(item)\n", " return tuple(result)" ], - "id": "c03c445284151c7c" + "id": "a9805aa4ff9a95c5" }, { "metadata": {}, @@ -1030,7 +1030,7 @@ "test_eq(flat_xt([x, x, [x,x]]), (x,)*4)\n", "test_eq(flat_xt(x), (x,))" ], - "id": "b194b91df7d94eeb" + "id": "37ba5f0377236658" }, { "metadata": {}, @@ -1044,7 +1044,7 @@ " def __init__(self, f, skip=None): self.f,self.skip = f,skip or []\n", " def __repr__(self): return f'Beforeware({self.f}, skip={self.skip})'" ], - "id": "6b7dbc73c0ee9956" + "id": "6174dca6668a1fb1" }, { "metadata": {}, @@ -1056,7 +1056,7 @@ "async def _handle(f, /, *args, **kwargs):\n", " return (await f(*args, **kwargs)) if is_async_callable(f) else await run_in_threadpool(f, *args, **kwargs)" ], - "id": "baf21aa39d330caa" + "id": "a96c2774bcd04b43" }, { "metadata": {}, @@ -1067,13 +1067,13 @@ "async def _f(f): return f\"got {f}\"\n", "test_eq(await _handle(_f, f='hello'), 'got hello')" ], - "id": "dd14420eb9df34c3" + "id": "2d0bc4359aa6fe36" }, { "metadata": {}, "cell_type": "markdown", "source": "## Websockets / SSE", - "id": "c7e4a0ee7bcfeeb7" + "id": "f6bb5d02c6c8864e" }, { "metadata": {}, @@ -1087,7 +1087,7 @@ " hdrs = Headers({k.lower():v for k,v in raw.items() if v is not None})\n", " return await _find_ps(ws, data, hdrs, params)" ], - "id": "ff2e3560134d8625" + "id": "153e3b1ea7055292" }, { "metadata": {}, @@ -1123,7 +1123,7 @@ " cls.on_receive = _recv\n", " return cls" ], - "id": "18b7eece28a161e6" + "id": "d0bb74c0505394bf" }, { "metadata": {}, @@ -1139,7 +1139,7 @@ " data = ws.receive_text()\n", " assert data == 'Message text was: Hi!', data" ], - "id": "4ba9a76b79dde97b" + "id": "f15042a7a6b760a3" }, { "metadata": {}, @@ -1154,7 +1154,7 @@ " data = ws.receive_text()\n", " assert data == 'trigger: my-btn', data\n" ], - "id": "3c9f31d17d2c4f38" + "id": "9188bc7533b849a9" }, { "metadata": {}, @@ -1167,7 +1167,7 @@ " \"Create a text/event-stream response from `s`\"\n", " return StreamingResponse(s, media_type=\"text/event-stream\")" ], - "id": "e6863a75509ad30f" + "id": "9f75ad3f2f434549" }, { "metadata": {}, @@ -1187,13 +1187,13 @@ " self._orig_handle_exit(*args, **kwargs)\n", " return event" ], - "id": "45597971e1e50d5e" + "id": "10ef6b0f6859260b" }, { "metadata": {}, "cell_type": "markdown", "source": "## Routing and application", - "id": "7ec729996815fee2" + "id": "e289aa9f0018eaf2" }, { "metadata": {}, @@ -1206,7 +1206,7 @@ " \"Create a URI by URL-encoding `_arg` and appending query parameters from `kwargs`\"\n", " return f\"{quote(_arg)}/{urlencode(kwargs, doseq=True)}\"" ], - "id": "530eae6fbdd9539c" + "id": "653fd1e031e7e909" }, { "metadata": {}, @@ -1220,7 +1220,7 @@ " arg,_,kw = s.partition('/')\n", " return unquote(arg), {k:v[0] for k,v in parse_qs(kw).items()}" ], - "id": "e2a698806339055" + "id": "7b5165962e556c08" }, { "metadata": {}, @@ -1231,7 +1231,7 @@ "#| export\n", "from starlette.convertors import StringConvertor" ], - "id": "4807df742dbb80d1" + "id": "c97237df628aa637" }, { "metadata": {}, @@ -1249,7 +1249,7 @@ " # assert value, \"Must not be empty\" # line removed due to errors\n", " return value" ], - "id": "2d21bc37c076b635" + "id": "788114a9c471742a" }, { "metadata": {}, @@ -1263,7 +1263,7 @@ " lp = self.scope['app'].url_path_for(name, **path_params)\n", " return URLPath(f\"{self.scope['root_path']}{lp}\", lp.protocol, lp.host)" ], - "id": "770c2ff543026748" + "id": "28bdbabfab30eeb9" }, { "metadata": {}, @@ -1297,7 +1297,7 @@ " _find_targets(req, resp)\n", " return to_xml(resp, indent=indent)" ], - "id": "3c4b16489e6e3d54" + "id": "6b905eb0992d1f6c" }, { "metadata": {}, @@ -1308,7 +1308,7 @@ "#| export\n", "_iter_typs = (tuple,list,map,filter,range,types.GeneratorType)" ], - "id": "131028d5ce8bec84" + "id": "cc183ea253dc4a5" }, { "metadata": {}, @@ -1327,7 +1327,7 @@ " else: result.append(item)\n", " return tuple(result)" ], - "id": "783da4cec6e383e5" + "id": "bd5994ad1f97d4dc" }, { "metadata": {}, @@ -1340,7 +1340,7 @@ " \"Default Body wrap function which just returns the content\"\n", " return c" ], - "id": "6d43e7902f33976c" + "id": "2f0ed8c4a7f04612" }, { "metadata": {}, @@ -1357,7 +1357,7 @@ " body = Body(body_wrap(*bw_args), *flat_xt(req.ftrs), **req.bodykw)\n", " return Html(Head(*heads, *flat_xt(req.hdrs)), body, **req.htmlkw)" ], - "id": "a0a10c614c784090" + "id": "9acad59a7635407e" }, { "metadata": {}, @@ -1366,7 +1366,7 @@ "Render fragment if `HX-Request` header is _present_ and\n", " `HX-History-Restore-Request` header is _absent._" ], - "id": "156bef4057dde28c" + "id": "e8c2481ee1749003" }, { "metadata": {}, @@ -1380,7 +1380,7 @@ " if resp and any(getattr(o, 'tag', '')=='html' for o in resp): return True\n", " return 'hx-request' in req.headers and 'hx-history-restore-request' not in req.headers" ], - "id": "e0f01932b6543d7c" + "id": "26de0211057e7bc" }, { "metadata": {}, @@ -1405,7 +1405,7 @@ " if len(resp)==1: resp = resp[0]\n", " return resp,kw" ], - "id": "6412519625d5d511" + "id": "d5f178af1a5d2f5f" }, { "metadata": {}, @@ -1429,7 +1429,7 @@ " resp = respond(req, [*heads, *title, *_canonical(req)], bdy)\n", " return _to_xml(req, resp, indent=fh_cfg.indent)" ], - "id": "2348b0e1d611ff62" + "id": "2db5544ac44ffbee" }, { "metadata": {}, @@ -1442,7 +1442,7 @@ " \"Check if response is a FastTag-compatible type\"\n", " return isinstance(resp, _iter_typs+(HttpHeader,FT)) or hasattr(resp, '__ft__')" ], - "id": "677001d8c8f92420" + "id": "4a494dc0787a67c2" }, { "metadata": {}, @@ -1470,7 +1470,7 @@ " cls = HTMLResponse\n", " return cls(resp, status_code=status_code, **kw)" ], - "id": "d2f2b62c8845f99c" + "id": "b10f16ab777cd471" }, { "metadata": {}, @@ -1486,7 +1486,7 @@ " if 'hx-request' in req.headers: return HtmxResponseHeaders(redirect=self.loc)\n", " return RedirectResponse(self.loc, status_code=303)" ], - "id": "688f836678719393" + "id": "1a4b6968c2791fd9" }, { "metadata": {}, @@ -1500,7 +1500,7 @@ " wreq = await _wrap_req(req, params)\n", " return await _handle(f, **wreq)" ], - "id": "68a4d195b0f137e9" + "id": "b1b70e9d57fe2224" }, { "metadata": {}, @@ -1528,13 +1528,13 @@ " \"multipart\": \"https://cdn.jsdelivr.net/npm/htmx.org@4.0.0/dist/ext/hx-multipart.min.js\"\n", "}" ], - "id": "b0b15a25a1f826d8" + "id": "9dc2a72097bb73cc" }, { "metadata": {}, "cell_type": "markdown", "source": "The FastHTML `exts` param supports the following:", - "id": "6b23ee6fde5e5b4b" + "id": "a44de325777a4e85" }, { "metadata": {}, @@ -1542,7 +1542,7 @@ "outputs": [], "execution_count": null, "source": "print(' '.join(htmx_exts))", - "id": "e4fbd2b25f5cb6ae" + "id": "35d1048f4bc1cca6" }, { "metadata": {}, @@ -1559,7 +1559,7 @@ "viewport = Meta(name=\"viewport\", content=\"width=device-width, initial-scale=1, viewport-fit=cover\")\n", "charset = Meta(charset=\"utf-8\")" ], - "id": "953ab02f6f985c28" + "id": "7de4b3490f3ff8a1" }, { "metadata": {}, @@ -1577,7 +1577,7 @@ " fname.write_text(key)\n", " return key" ], - "id": "6054a224e78e9366" + "id": "55027657b8ad63e2" }, { "metadata": {}, @@ -1590,7 +1590,7 @@ " \"Wrap non-list item in a list, returning empty list if None\"\n", " return [] if not o else list(o) if isinstance(o, (tuple,list)) else [o]" ], - "id": "57fd615f7415afa8" + "id": "4cccd862800e7ac" }, { "metadata": {}, @@ -1608,7 +1608,7 @@ " return _resp(req, res, status_code=status_code)\n", " return _f" ], - "id": "417f41f9a2b48a07" + "id": "7e1d96be2a459ff7" }, { "metadata": {}, @@ -1628,13 +1628,13 @@ " # encode query params\n", " return p + ('?' + urlencode({k:'' if v in (False,None) else v for k,v in kw.items()},doseq=True) if kw else '')" ], - "id": "3ac78cbb40aa5e1e" + "id": "c29274682fe83710" }, { "metadata": {}, "cell_type": "markdown", "source": "`qp` adds query parameters to route path strings", - "id": "d3c28cb2f39549c7" + "id": "5911decec03b9204" }, { "metadata": {}, @@ -1642,7 +1642,7 @@ "outputs": [], "execution_count": null, "source": "vals = dict(a=5, b=False, c=[1,2], d='bar', e=None, ab=42)", - "id": "1e90b2548c207f5" + "id": "6d5f08ed6b8d7eab" }, { "metadata": {}, @@ -1653,13 +1653,13 @@ "res = qp('/foo', **vals)\n", "test_eq(res, '/foo?a=5&b=&c=1&c=2&d=bar&e=&ab=42')" ], - "id": "4bb2dd90d99c0f69" + "id": "7ea36e9f3118cc31" }, { "metadata": {}, "cell_type": "markdown", "source": "`qp` checks to see if each param should be sent as a query parameter or as part of the route, and encodes that properly.", - "id": "1af3b977e4b6e939" + "id": "e9445227a177b6e9" }, { "metadata": {}, @@ -1671,7 +1671,7 @@ "res = qp(path, **vals)\n", "test_eq(res, '/foo/5/bar/42?b=&c=1&c=2&e=')" ], - "id": "14bcc36e075308b5" + "id": "20b8c42db7ceebac" }, { "metadata": {}, @@ -1692,7 +1692,7 @@ " elif htmx: hdrs = [htmxsrc,fhjsscr] + hdrs\n", " return [charset, viewport] + hdrs" ], - "id": "8687262d8af34d50" + "id": "61d229aa49526f9e" }, { "metadata": {}, @@ -1725,7 +1725,7 @@ " };\n", "\"\"\"))\n" ], - "id": "4c5e7deacc17f2dd" + "id": "9e9245d7151846d5" }, { "metadata": {}, @@ -1760,7 +1760,7 @@ "\n", " def on_event(self, event_type): return lambda f: (getattr(self, event_type)).append(f)" ], - "id": "5fcae44026df7b16" + "id": "922ae73cd9942576" }, { "metadata": {}, @@ -1807,13 +1807,13 @@ "\n", " def on_event(self, event_type): return self.lifespan.on_event(event_type)" ], - "id": "e7a1793e81819075" + "id": "8280ab77b004c7fd" }, { "metadata": {}, "cell_type": "markdown", "source": "### Routes", - "id": "6e4e5231cea40245" + "id": "87f24b23458952ab" }, { "metadata": {}, @@ -1839,7 +1839,7 @@ " methods = sorted(self.methods or [])\n", " return f\"{self.__class__.__name__}(path={self.path!r}, name={self.name!r}, methods={methods!r}, host={self.host!r})\"" ], - "id": "fee720e4fcd081ab" + "id": "cbced2560121728f" }, { "metadata": {}, @@ -1859,7 +1859,7 @@ "test_eq(cli.get('/', headers={'host': 'auth.example.com'}).text, 'auth page')\n", "print('all passed')" ], - "id": "6e3938b28bfa688f" + "id": "53915be81ac4c15b" }, { "metadata": {}, @@ -1875,7 +1875,7 @@ "test_eq(cli.get('/hello', headers={'host': 'other.mysite.com'}).text, 'normal hello')\n", "print('all passed')" ], - "id": "68eee5aa5ce04ade" + "id": "28de7f0b0f018e4f" }, { "metadata": {}, @@ -1894,7 +1894,7 @@ " self.router.routes.append(route)\n", " self.router.routes.sort(key=lambda r: not getattr(r, 'host', None))\n" ], - "id": "761915f262a753d4" + "id": "a0353d195d85b41f" }, { "metadata": {}, @@ -1905,7 +1905,7 @@ "#| export\n", "all_meths = 'get post put delete patch head trace options'.split()" ], - "id": "62590e9b8aa56156" + "id": "35e92f834eaf7838" }, { "metadata": {}, @@ -1942,7 +1942,7 @@ " return _resp(req, resp, sig.return_annotation)\n", " return _f" ], - "id": "8b820ee5ecd21e1c" + "id": "8dc6cc8ead47bada" }, { "metadata": {}, @@ -1960,7 +1960,7 @@ " self.add_route(route)\n", " return func" ], - "id": "d23d12b26b62e05" + "id": "3807657597615741" }, { "metadata": {}, @@ -1975,7 +1975,7 @@ " def f(func=noop): return self._add_ws(func, path, conn, disconn, name=name, middleware=middleware)\n", " return f" ], - "id": "c6597341785b1226" + "id": "ec1666b6c1071021" }, { "metadata": {}, @@ -1989,7 +1989,7 @@ " \"Add a websocket route at `path` (Starlette-compatible API)\"\n", " return self._add_ws(func, path, conn, disconn, name=name, middleware=middleware)" ], - "id": "e9208c48e6a7d964" + "id": "f9de41431ec94bdc" }, { "metadata": {}, @@ -2011,7 +2011,7 @@ "\n", " return _lf()" ], - "id": "5803286e07e2dd6c" + "id": "3c2e5449180b4487" }, { "metadata": {}, @@ -2024,7 +2024,7 @@ " \"Get name of function `f` using '_' to join nested function names\"\n", " return f.__qualname__.replace('..', '_')" ], - "id": "61504e932bcb6453" + "id": "afd2d5e724c31a07" }, { "metadata": {}, @@ -2036,7 +2036,7 @@ " def g(): ...\n", " return g" ], - "id": "459aa1caff394061" + "id": "d8c0c55c5dad21e5" }, { "metadata": {}, @@ -2047,7 +2047,7 @@ "func = f()\n", "nested_name(func)" ], - "id": "c3311e187ab0c525" + "id": "a4130fc1830f5d5" }, { "metadata": {}, @@ -2067,7 +2067,7 @@ " if handler: self._add_route(handler, path, meth, name, include_in_schema, body_wrap, host=host, before=before)\n", " return lf" ], - "id": "79202eff3271765a" + "id": "27991d742be3027b" }, { "metadata": {}, @@ -2100,7 +2100,7 @@ " lf.__routename__ = n\n", " return lf" ], - "id": "519bd9038c86b0d7" + "id": "17141c4b6b43dab4" }, { "metadata": {}, @@ -2118,7 +2118,7 @@ "\n", "for o in all_meths: setattr(FastHTML, o, partialmethod(FastHTML.route, methods=o))" ], - "id": "25ae3aa5f868f44a" + "id": "71c2e5b68940c3a" }, { "metadata": {}, @@ -2132,7 +2132,7 @@ "\n", "foo.to(a='bar', b=[1,2])" ], - "id": "b10bfcb7a593ee05" + "id": "ee00e8824e619da9" }, { "metadata": {}, @@ -2145,13 +2145,13 @@ "\n", "foo.to(a='bar', b=[1,2])" ], - "id": "fbe6c053bf35cb87" + "id": "404c3c2a9a208c00" }, { "metadata": {}, "cell_type": "markdown", "source": "### Utils", - "id": "f2ed69bbaf963475" + "id": "f4458f66fb534b88" }, { "metadata": {}, @@ -2166,7 +2166,7 @@ " if inspect.isasyncgenfunction(value): value = contextlib.asynccontextmanager(value)\n", " self.router.lifespan_context = value" ], - "id": "8395cef9c2dea921" + "id": "164ae4c080e3a203" }, { "metadata": {}, @@ -2200,13 +2200,13 @@ " print('Link: '+ S.light_red.bold(link))\n", " run(f'{appname}:{app}', host=host, port=port, reload=reload, **kwargs)" ], - "id": "949365706b509933" + "id": "574599ab8e485128" }, { "metadata": {}, "cell_type": "markdown", "source": "`procs` runs the app as that many processes on consecutive ports from `port`, each with its own reload supervisor, and defaults to the `PROCS` environment variable. `serve` re-executes the script once per process with `FH_PROCNUM` set to its number, which is also the guard against a child spawning again. An app reads `FH_PROCNUM` for work that only one process should do, such as a background job: it is `'0'` in the first process, and unset in an ordinary single-process run. A reverse proxy in front of the ports decides how requests reach them.", - "id": "944609fe9b5f5360" + "id": "ba8f3772458e5efd" }, { "metadata": {}, @@ -2221,13 +2221,13 @@ " signal.signal(signal.SIGTERM, lambda *a: [p.terminate() for p in ps])\n", " for p in ps: p.wait()" ], - "id": "9923dbe3e6937f09" + "id": "42e0824c2b6e6f96" }, { "metadata": {}, "cell_type": "markdown", "source": "Starlette does not cancel a running handler when a client disconnects: the disconnect is only visible as an `http.disconnect` message on the ASGI receive channel, which ordinary handlers never read. `until_disconnect` races a coroutine against that message, cancelling the work if the client goes away first.", - "id": "c6739d867595760d" + "id": "a4c783f2477c0aed" }, { "metadata": {}, @@ -2250,13 +2250,13 @@ " watch.cancel()\n", " if not work.done(): work.cancel()" ], - "id": "d6f51e6ddabb5426" + "id": "51ce29d7628bf1b8" }, { "metadata": {}, "cell_type": "markdown", "source": "`cancel_on_disconnect` applies this to a route handler. `splice_sig` adds a private `Request`-annotated parameter to the exposed signature, which FastHTML fills with the connection, so the handler's own parameters are unchanged. It requires an async handler, since a sync handler runs in a threadpool and cannot be cancelled.", - "id": "8987f8795854b0d3" + "id": "6126083ca89e04bc" }, { "metadata": {}, @@ -2278,7 +2278,7 @@ " return await (asyncio.wait_for(c, timeout) if timeout is not None else c)\n", " return splice_sig(_f, f)" ], - "id": "9b289597ccc85bb0" + "id": "28185ffcbd0606f3" }, { "metadata": {}, @@ -2299,7 +2299,7 @@ "\n", "for o in ('get', 'post', 'delete', 'put', 'patch', 'options'): setattr(Client, o, partialmethod(Client._sync, o))" ], - "id": "2d9f445812e61010" + "id": "fee17876aac0991e" }, { "metadata": {}, @@ -2312,19 +2312,19 @@ "\n", "cli.get('/').text" ], - "id": "a0d50c343884f7" + "id": "8b41ad04a601516e" }, { "metadata": {}, "cell_type": "markdown", "source": "Note that you can also use Starlette's `TestClient` instead of FastHTML's `Client`. They should be largely interchangable.", - "id": "acbf8b7311f723fd" + "id": "e846f30998cb91ed" }, { "metadata": {}, "cell_type": "markdown", "source": "## FastHTML Tests", - "id": "1ace95eeec5d7233" + "id": "563002946f61b59d" }, { "metadata": {}, @@ -2332,7 +2332,7 @@ "outputs": [], "execution_count": null, "source": "def get_cli(app): return app,TestClient(app),app.route", - "id": "11278015a711f50" + "id": "8b5d1b7481cf821d" }, { "metadata": {}, @@ -2340,7 +2340,7 @@ "outputs": [], "execution_count": null, "source": "app,cli,rt = get_cli(FastHTML(secret_key='soopersecret'))", - "id": "876cfcb58fff09be" + "id": "d56ba963ff739e47" }, { "metadata": {}, @@ -2359,7 +2359,7 @@ "\n", "foo.to(param='value')" ], - "id": "d223d27ab2024726" + "id": "f44f9f513b92e52e" }, { "metadata": {}, @@ -2375,7 +2375,7 @@ "assert \"Goodbye World\" in cli.get('/foo', headers={'host': 'test.foo'}).text\n", "assert \"Hello World\" in cli.get('/foo').text" ], - "id": "e9ad23318cd58f72" + "id": "eda0d3ca130a9d3" }, { "metadata": {}, @@ -2388,7 +2388,7 @@ "\n", "foo.to(param='value')" ], - "id": "845c8d8cd8b678e2" + "id": "ee108bfb8959d071" }, { "metadata": {}, @@ -2404,7 +2404,7 @@ "txt = cli.get('/xt2').text\n", "assert 'FastHTML page' in txt and '

bar

' in txt and '' in txt" ], - "id": "ad7c328b17fdf13b" + "id": "1b1f6ee66ad7f95" }, { "metadata": {}, @@ -2416,7 +2416,7 @@ " if hx: kwargs['headers'] = {'hx-request':\"1\"}\n", " test_eq(getattr(cli, meth)(path, **kwargs).text, exp)" ], - "id": "840a147f46b96daa" + "id": "f96b6a88b07ebc3c" }, { "metadata": {}, @@ -2438,7 +2438,7 @@ "test_eq(cli.delete('/class-cards/abc').text, 'delete abc')\n", "test_eq(CardMethods.to(id='xyz'), '/class-cards/xyz')" ], - "id": "14d777ba36c4523e" + "id": "5069dc1e088ac131" }, { "metadata": {}, @@ -2453,7 +2453,7 @@ "test_eq(cli.get('/things?id=7').text, 'thing 7')\n", "test_eq(Things.to(id=7), '/things?id=7')" ], - "id": "89010e5a319a1ee" + "id": "c8e001bbbb8d7e6" }, { "metadata": {}, @@ -2467,7 +2467,7 @@ "r = cli.get('/hi')\n", "r.text" ], - "id": "ab04bc8df2f0627c" + "id": "440454b57f7ce9ae" }, { "metadata": {}, @@ -2480,7 +2480,7 @@ "\n", "cli.post('/hi').text" ], - "id": "87f365d396f69614" + "id": "2da404e86f7bb4f1" }, { "metadata": {}, @@ -2493,7 +2493,7 @@ "\n", "cli.get('/hostie').text" ], - "id": "c2f7aff939dc9838" + "id": "9db1e91bd3587b82" }, { "metadata": {}, @@ -2516,7 +2516,7 @@ "assert 'Message text was: Hi! with session bar' in data\n", "print(data)" ], - "id": "67c8fd44c79ba121" + "id": "ac41993d2227dee8" }, { "metadata": {}, @@ -2529,7 +2529,7 @@ "\n", "cli.post('/yoyo').text" ], - "id": "11bf1da78fa14eed" + "id": "8933972cfc996310" }, { "metadata": {}, @@ -2541,7 +2541,7 @@ "def autopost(): return Html(Div('Text.', hx_post=yoyo()))\n", "print(cli.get('/autopost').text)" ], - "id": "bf550a863e622bb1" + "id": "f940e03bffe4c66" }, { "metadata": {}, @@ -2553,7 +2553,7 @@ "def autopost2(): return Html(Body(Div('Text.', cls='px-2', hx_post=show_host.to(a='b'))))\n", "print(cli.get('/autopost2').text)" ], - "id": "5c264fec32f081e0" + "id": "b04025027d08127e" }, { "metadata": {}, @@ -2565,7 +2565,7 @@ "def autoget2(): return Html(Div('Text.', hx_get=show_host))\n", "print(cli.get('/autoget2').text)" ], - "id": "cb14ea89414940fb" + "id": "23d8293222046546" }, { "metadata": {}, @@ -2577,7 +2577,7 @@ "def get(nm:str=''): return f\"Good day to you, {nm}!\"\n", "cli.get('/user/Alexis').text" ], - "id": "561f7d3538fc1228" + "id": "9136c213aeade42c" }, { "metadata": {}, @@ -2589,7 +2589,7 @@ "def autolink(): return Html(Div('Text.', link=uri('gday', nm='Alexis')))\n", "print(cli.get('/autolink').text)" ], - "id": "418113e5fa132dd5" + "id": "89e89849ef44bbd9" }, { "metadata": {}, @@ -2602,7 +2602,7 @@ "\n", "cli.get('/link').text" ], - "id": "3909c1dd3e3392c4" + "id": "6b31ac100fa4e29a" }, { "metadata": {}, @@ -2619,7 +2619,7 @@ "\n", "response = cli.get(\"/background\")" ], - "id": "90716a3aea939978" + "id": "eff23aa20278ed13" }, { "metadata": {}, @@ -2627,7 +2627,7 @@ "outputs": [], "execution_count": null, "source": "test_eq(app.router.url_path_for('gday', nm='Jeremy'), '/user/Jeremy')", - "id": "1966de3a3b6b0b51" + "id": "e9a57394568c59ef" }, { "metadata": {}, @@ -2657,7 +2657,7 @@ "txt = cli.get('/xt3').text\n", "assert 'FastHTML page' not in txt and 'hi' in txt and '

there

' in txt" ], - "id": "338a57122f4d7622" + "id": "c93af6bf798b70fb" }, { "metadata": {}, @@ -2671,7 +2671,7 @@ "test_warns(lambda: rt('/oops')(_noanno))\n", "test_warns(lambda: rt('/barelist')(_bare))" ], - "id": "224151e95a080e42" + "id": "acba8d0b1b3d138b" }, { "metadata": {}, @@ -2683,7 +2683,7 @@ "test_warns(lambda: cli.get('/oops?nope=1'))\n", "test_warns(lambda: cli.get('/barelist?names=1'))" ], - "id": "ed0f5226db71a55b" + "id": "9fbd96cb6f2da337" }, { "metadata": {}, @@ -2694,7 +2694,7 @@ "ModelName = str_enum('ModelName', \"alexnet\", \"resnet\", \"lenet\")\n", "fake_db = [{\"name\": \"Foo\"}, {\"name\": \"Bar\"}]" ], - "id": "f8abfe73aa7e665b" + "id": "dfd5682d7f9b074c" }, { "metadata": {}, @@ -2705,7 +2705,7 @@ "@rt('/html/{idx}')\n", "async def get(idx:int): return Body(H4(f'Next is {idx+1}.'))" ], - "id": "c9be8b9a13c7b" + "id": "648f2d8a096744bc" }, { "metadata": {}, @@ -2731,7 +2731,7 @@ "@rt(\"/unionidxl/\")\n", "def get(idx:list[int] | None): return str(idx)" ], - "id": "c09b199ed001f5c7" + "id": "b7fcad6b61e4df59" }, { "metadata": {}, @@ -2752,7 +2752,7 @@ "test_r(cli, '/optidxl/?idx=1&idx=2', '[1, 2]')\n", "test_r(cli, '/unionidxl/?idx=1&idx=2', '[1, 2]')" ], - "id": "ec2f7f8a97792fd" + "id": "ec5e76ebe3e0fcdc" }, { "metadata": {}, @@ -2769,7 +2769,7 @@ "def foo(path:str, a:int): return f'also got {path},{a}'\n", "cli.get('/static/sub/a.b.jpg').text" ], - "id": "806bd5c5b8214027" + "id": "76db7d976388e3ec" }, { "metadata": {}, @@ -2777,7 +2777,7 @@ "outputs": [], "execution_count": null, "source": "cli.get('/static/sub/a.b?a=1').text", - "id": "41ad4d0dae24e431" + "id": "d8c35fedaf3130e0" }, { "metadata": {}, @@ -2785,7 +2785,7 @@ "outputs": [], "execution_count": null, "source": "app.chk = 'foo'", - "id": "270b73ac388beec3" + "id": "adb6052f90c3a166" }, { "metadata": {}, @@ -2820,7 +2820,7 @@ "@app.get(\"/app4\")\n", "def _(foo:FastHTML): return Redirect(\"http://example.org\")" ], - "id": "5bb28848fd83279f" + "id": "3355a8e4230211c3" }, { "metadata": {}, @@ -2837,7 +2837,7 @@ "test_r(cli, '/hxtest2', '1', headers={'HX-Request':'1'})\n", "test_r(cli, '/app' , 'foo')" ], - "id": "46d098bb8867c394" + "id": "ca78bc1e62c94de1" }, { "metadata": {}, @@ -2849,7 +2849,7 @@ "test_eq(r.text, 'foo')\n", "test_eq(r.headers['mykey'], 'myval')" ], - "id": "cf42935badd43f5f" + "id": "eb9844fe5290f911" }, { "metadata": {}, @@ -2860,7 +2860,7 @@ "r = cli.get('/app3')\n", "test_eq(r.headers['HX-Location'], 'http://example.org')" ], - "id": "925cf36bab1b36bd" + "id": "2df9561ed1ec0085" }, { "metadata": {}, @@ -2871,7 +2871,7 @@ "r = cli.get('/app4', follow_redirects=False)\n", "test_eq(r.status_code, 303)" ], - "id": "57f7ee8411e7b167" + "id": "7833151d129fc2d7" }, { "metadata": {}, @@ -2882,7 +2882,7 @@ "r = cli.get('/app4', headers={'HX-Request':'1'})\n", "test_eq(r.headers['HX-Redirect'], 'http://example.org')" ], - "id": "8dd137ec345034ec" + "id": "bda0ae61b5aeaf0c" }, { "metadata": {}, @@ -2897,7 +2897,7 @@ "assert re.search(r'\\s*

hi

\\s*', t)\n", "assert 'It worked!\" in response and \"

15, Lorem

\" in response" ], - "id": "ec3b771e001ee9c7" + "id": "ee29c6f876467832" }, { "metadata": {}, @@ -3025,7 +3025,7 @@ "response = cli.post('/bodytext', headers={\"Content-Type\": \"application/json\"}, data=s).text\n", "test_eq(response, '{\"b\": \"Lorem\", \"a\": 15}')" ], - "id": "98e17f17ef0dc78a" + "id": "1d9465be7d5e9787" }, { "metadata": {}, @@ -3033,7 +3033,7 @@ "outputs": [], "execution_count": null, "source": "files = [('files', ('file1.txt', b'content1')), ('files', ('file2.txt', b'content2'))]", - "id": "ec6e5345e542ab55" + "id": "bbedc4be762d75c9" }, { "metadata": {}, @@ -3048,7 +3048,7 @@ "print(res.status_code)\n", "print(res.text)" ], - "id": "2c61b6a60b3540d6" + "id": "37fd179f35c4e3c7" }, { "metadata": {}, @@ -3060,7 +3060,7 @@ "test_eq(res.status_code, 200)\n", "test_eq(res.text, 'content1')" ], - "id": "7ec54f9bf1c48765" + "id": "c32f163bf5a0c20e" }, { "metadata": {}, @@ -3082,7 +3082,7 @@ "\n", "cli.get('/getsess').text" ], - "id": "aad9b9ce36863a63" + "id": "bc8e585ac460015a" }, { "metadata": {}, @@ -3102,7 +3102,7 @@ "\n", "test_eq(cli.get('/getsess-all').text, '2')" ], - "id": "34c2f446da12947a" + "id": "2cd966578e7cfd63" }, { "metadata": {}, @@ -3115,7 +3115,7 @@ "\n", "with open('../../CHANGELOG.md', 'rb') as f: print(cli.post('/upload', files={'uf':f}, data={'msg':'Hello'}).text[:15])" ], - "id": "c92b006916962f75" + "id": "60526ff4cd5c9078" }, { "metadata": {}, @@ -3128,7 +3128,7 @@ " headers = {'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'POST', 'Access-Control-Allow-Headers': '*'}\n", " return Response(status_code=200, headers=headers)" ], - "id": "ec51f25bd3652cd1" + "id": "47b2906ce18cd5fd" }, { "metadata": {}, @@ -3139,7 +3139,7 @@ "h = cli.options('/form-submit/2').headers\n", "test_eq(h['Access-Control-Allow-Methods'], 'POST')" ], - "id": "d460e6dbdb8dd934" + "id": "8ab8b6f7ff4931ed" }, { "metadata": {}, @@ -3147,7 +3147,7 @@ "outputs": [], "execution_count": null, "source": "from fasthtml.authmw import user_pwd_auth", - "id": "3d7dbed27003480a" + "id": "4eccbbe382abb504" }, { "metadata": {}, @@ -3163,7 +3163,7 @@ "assert '
nope
' in txt\n", "assert '' in txt" ], - "id": "864cf99f2c3ae7e4" + "id": "661b219db32534c3" }, { "metadata": {}, @@ -3179,7 +3179,7 @@ "assert 'Hello Uma, age 5' in cli.get('/uma/5').text\n", "assert '404 Not Found' in cli.get('/uma/five').text" ], - "id": "ec071d4434f7b01e" + "id": "ad2613a30250c03f" }, { "metadata": {}, @@ -3196,7 +3196,7 @@ "test_eq(cli.get('/locked').text, 'not authenticated')\n", "test_eq(cli.get('/locked', auth=(\"testuser\",\"spycraft\")).text, 'Hello, testuser')" ], - "id": "f5690664c11111c3" + "id": "698f2aef7c379644" }, { "metadata": {}, @@ -3213,13 +3213,13 @@ "test_eq(cli.get('/locked').text, 'not authenticated')\n", "test_eq(cli.get('/locked', auth=(\"testuser\",\"spycraft\")).text, 'Hello, testuser')" ], - "id": "35906bc86879e702" + "id": "638daedb404c11de" }, { "metadata": {}, "cell_type": "markdown", "source": "Check that afterware like toasts are called correctly.", - "id": "715da9a9f886acdb" + "id": "4020afeba6268102" }, { "metadata": {}, @@ -3227,7 +3227,7 @@ "outputs": [], "execution_count": null, "source": "from fasthtml.toaster import *", - "id": "e097e6f2f34810bc" + "id": "e4462cee346d27d7" }, { "metadata": {}, @@ -3269,13 +3269,13 @@ "r = cli.get('/')\n", "assert tm in r.text" ], - "id": "a1b6328777990e33" + "id": "9049f79617eecaa6" }, { "metadata": {}, "cell_type": "markdown", "source": "Here's a quick sanity check to confirm that toasts are rendered in the toast container correctly. See [issue](https://github.com/AnswerDotAI/fasthtml/issues/762).", - "id": "71feed8c8eec723c" + "id": "18ccaa96af7b278b" }, { "metadata": {}, @@ -3283,7 +3283,7 @@ "outputs": [], "execution_count": null, "source": "assert 'id=\"fh-toast-container\"' in r.text", - "id": "37285b1359490d0a" + "id": "274f84a3d05dbe24" }, { "metadata": {}, @@ -3300,7 +3300,7 @@ "with cli: test_eq(cli.get('/').text, 'True')\n", "test_eq(app._stopped, True)" ], - "id": "3911e2efa6eff2f7" + "id": "ed8a54535297c248" }, { "metadata": {}, @@ -3318,13 +3318,13 @@ "\n", "with cli: test_eq(cli.get('/').text, 'fired')" ], - "id": "31ea8e937c9f18cb" + "id": "3b86251628c330d7" }, { "metadata": {}, "cell_type": "markdown", "source": "A route-level `before` can set session data, short-circuit with a response, or raise to block access:", - "id": "913d1b3cb80c4d0c" + "id": "6da261c96ffba230" }, { "metadata": {}, @@ -3346,13 +3346,13 @@ "test_eq(cli.get('/dashboard?user=guest').text, 'guest view')\n", "test_eq(cli.get('/dashboard?user=other').status_code, 403)" ], - "id": "42b7166381b2de31" + "id": "89bc4b12f61ed190" }, { "metadata": {}, "cell_type": "markdown", "source": "Multiple `before` functions run in order, each receiving the injected request params:", - "id": "f827e72640085b2f" + "id": "8500b1d4bb69062f" }, { "metadata": {}, @@ -3368,13 +3368,13 @@ "\n", "test_eq(cli.get('/multi').text, '1,2')" ], - "id": "63ab236a7e4c8b5e" + "id": "beda57687e9b441b" }, { "metadata": {}, "cell_type": "markdown", "source": "A truthy return from any `before` becomes the response; remaining `before`s and the handler are skipped (return `None` to continue):", - "id": "ecba79afd0c3b9e8" + "id": "1570578c8e6cde86" }, { "metadata": {}, @@ -3394,13 +3394,13 @@ "test_eq(cli.get('/chain').text, 'stop')\n", "test_eq(calls, ['first'])" ], - "id": "b834f3053cdaaff5" + "id": "463863760a263190" }, { "metadata": {}, "cell_type": "markdown", "source": "`cancel_on_disconnect` handlers keep their normal parameters; the handler is cancelled if the client disconnects, or after `timeout` seconds if given:", - "id": "86b74f597dc5d2e9" + "id": "5aaa0a68c07da574" }, { "metadata": {}, @@ -3416,7 +3416,7 @@ "\n", "test_eq(cli.get('/cq?q=x').text, 'got x')" ], - "id": "e64d3e485aa691fd" + "id": "f8e35000c65ba62e" }, { "metadata": {}, @@ -3432,13 +3432,13 @@ "\n", "test_fail(lambda: cli.get('/sleepy'))" ], - "id": "d11b1608d51eb867" + "id": "7b9172d10408c9ed" }, { "metadata": {}, "cell_type": "markdown", "source": "On disconnect the handler is cancelled and an empty response returned, which the server discards since the client is gone. Here we simulate the ASGI `http.disconnect` message directly:", - "id": "78bcb538beffc3c1" + "id": "2e83b131027a820f" }, { "metadata": {}, @@ -3463,13 +3463,13 @@ "test_eq(run_sync(_t()).status_code, 204)\n", "test_eq(cancelled, [True])" ], - "id": "d9b6647ef0b1c120" + "id": "e35eda8d436c0d7a" }, { "metadata": {}, "cell_type": "markdown", "source": "## APIRouter", - "id": "a3ef3aafeed1c543" + "id": "14d4f5f2940dddc4" }, { "metadata": {}, @@ -3488,7 +3488,7 @@ " except KeyError: raise AttributeError(f\"No route named {name} found in route functions\")\n", " def __dir__(self): return list(self._funcs.keys())" ], - "id": "8d1ad3aa405f8952" + "id": "2c8672873fd6eff4" }, { "metadata": {}, @@ -3536,7 +3536,7 @@ " def f(func=noop): return self.wss.append((func, f\"{self.prefix}{path}\", conn, disconn, name, middleware))\n", " return f" ], - "id": "93fc46fe69d90aa2" + "id": "2bea13758101b485" }, { "metadata": {}, @@ -3544,7 +3544,7 @@ "outputs": [], "execution_count": null, "source": "ar = APIRouter()", - "id": "b5410d5e8e309c99" + "id": "4e8eb2f750a573da" }, { "metadata": {}, @@ -3574,7 +3574,7 @@ "@ar.ws(\"/ws\")\n", "def ws(self, msg:str): return f\"Message text was: {msg}\"" ], - "id": "2bf8cf65a3dd1945" + "id": "621317c4291a63d3" }, { "metadata": {}, @@ -3585,7 +3585,7 @@ "app,cli,_ = get_cli(FastHTML())\n", "ar.to_app(app)" ], - "id": "8b3f8ed2df1bde26" + "id": "1ced9d3e7dc0374d" }, { "metadata": {}, @@ -3603,7 +3603,7 @@ "# ensure any route functions named using an HTTPMethod are not discoverable via `rt_funcs`\n", "assert \"get\" not in ar.rt_funcs._funcs.keys()" ], - "id": "73718966d4787400" + "id": "d671af83ebfebba6" }, { "metadata": {}, @@ -3624,7 +3624,7 @@ "test_eq(cli.delete('/class-cards/abc').text, 'delete abc')\n", "test_eq(CardMethods.to(id='xyz'), '/class-cards/xyz')" ], - "id": "5acb58e120365823" + "id": "9f1a50df1b889859" }, { "metadata": {}, @@ -3637,7 +3637,7 @@ " data = ws.receive_text()\n", " assert data == 'Message text was: Hi!'" ], - "id": "5ac26b06271b614" + "id": "53ab520c3de086b6" }, { "metadata": {}, @@ -3645,7 +3645,7 @@ "outputs": [], "execution_count": null, "source": "ar2 = APIRouter(\"/products\")", - "id": "26ba77d9d7360fe8" + "id": "ae401717e3e65a44" }, { "metadata": {}, @@ -3673,7 +3673,7 @@ "@ar2.ws(\"/ws\")\n", "def ws(self, msg:str): return f\"Message text was: {msg}\"" ], - "id": "8be654b68b7e4fd6" + "id": "dc835f3656eaf5c1" }, { "metadata": {}, @@ -3684,7 +3684,7 @@ "app,cli,_ = get_cli(FastHTML())\n", "ar2.to_app(app)" ], - "id": "71d836196c32426d" + "id": "791efcb188f97aaf" }, { "metadata": {}, @@ -3701,7 +3701,7 @@ "with ExceptionExpected(): ar2.rt_funcs.blah()\n", "assert \"get\" not in ar2.rt_funcs._funcs.keys()" ], - "id": "b4acf9b9badda242" + "id": "1ecad744ef2b3f5d" }, { "metadata": {}, @@ -3720,7 +3720,7 @@ "test_eq(cli.get('/products/products?id=7').text, 'product 7')\n", "test_eq(Products.to(id=7), '/products/products?id=7')" ], - "id": "1a999d4fe38dc396" + "id": "8298ed03030b8235" }, { "metadata": {}, @@ -3733,7 +3733,7 @@ " data = ws.receive_text()\n", " assert data == 'Message text was: Hi!'" ], - "id": "a3201869573175c1" + "id": "6a11faba637e0598" }, { "metadata": {}, @@ -3744,7 +3744,7 @@ "#| export\n", "for o in all_meths: setattr(APIRouter, o, partialmethod(APIRouter.__call__, methods=o))" ], - "id": "1859d1c226783abe" + "id": "7520fe3f75ff0273" }, { "metadata": {}, @@ -3766,13 +3766,13 @@ "@ar2.post(\"/post2\")\n", "def _(): return 'Postal'" ], - "id": "3f2e9dfaf07906ad" + "id": "9d3e5f1dfc4454a5" }, { "metadata": {}, "cell_type": "markdown", "source": "## Extras", - "id": "cefabdfd3804ce65" + "id": "cb33740f9931b567" }, { "metadata": {}, @@ -3780,7 +3780,7 @@ "outputs": [], "execution_count": null, "source": "app,cli,rt = get_cli(FastHTML(secret_key='soopersecret'))", - "id": "f4f134d385ba979c" + "id": "be443700247fb92e" }, { "metadata": {}, @@ -3805,7 +3805,7 @@ " cookie_val = cookie.output(header=\"\").strip()\n", " return HttpHeader(\"set-cookie\", cookie_val)" ], - "id": "8db47f8de086a404" + "id": "5b54ca7b445b95d0" }, { "metadata": {}, @@ -3823,7 +3823,7 @@ "time.sleep(0.01)\n", "cli.get('/getcookie').text" ], - "id": "b83427dfe5a39ae8" + "id": "ded4799ac019dbe7" }, { "metadata": {}, @@ -3837,7 +3837,7 @@ " cls = get_class(f'{m}Conv', sup=StringConvertor, regex=s)\n", " register_url_convertor(m, cls())" ], - "id": "d18e6ecc94583abc" + "id": "b15d17a5c6de19c2" }, { "metadata": {}, @@ -3857,7 +3857,7 @@ " @self.get(f\"{prefix}{{fname:path}}.{{ext:{exts}}}\")\n", " async def get(fname:str, ext:str): return FileResponse(f'{static_path}/{fname}.{ext}')" ], - "id": "88b7340a78a5e97c" + "id": "da7cf380b731da02" }, { "metadata": {}, @@ -3872,7 +3872,7 @@ "\n", "test_r(cli, '/static/foo/jph.me.ico', 'Getting jph.me.ico from /foo/')" ], - "id": "dd357f05f363eddb" + "id": "ac5723265cb90da3" }, { "metadata": {}, @@ -3883,7 +3883,7 @@ "app.static_route_exts()\n", "assert 'These are the source notebooks for FastHTML' in cli.get('/README.txt').text" ], - "id": "7e6039c9c6cc9e" + "id": "261b16cb45660e65" }, { "metadata": {}, @@ -3898,7 +3898,7 @@ " @self.get(f\"{prefix}{{fname:path}}{ext}\")\n", " async def get(fname:str): return FileResponse(f'{static_path}/{fname}{ext}')" ], - "id": "4433cd8119244424" + "id": "baea241aa4415b80" }, { "metadata": {}, @@ -3909,7 +3909,7 @@ "app.static_route('.md', static_path='../..')\n", "assert 'THIS FILE WAS AUTOGENERATED' in cli.get('/README.md').text" ], - "id": "2f661b66f3e94173" + "id": "2b1d76f47e6c504" }, { "metadata": {}, @@ -3925,7 +3925,7 @@ " resp.headers.setdefault(\"Cache-Control\", \"no-cache\")\n", " return resp" ], - "id": "7dd76a7c38bf4ec0" + "id": "cbdb4ced4c5f2fd" }, { "metadata": {}, @@ -3941,13 +3941,13 @@ " resp.headers.setdefault(\"Cache-Control\", \"public, max-age=31536000, immutable\")\n", " return resp" ], - "id": "341dff8d4f8feb92" + "id": "46c42cf52af0cf6" }, { "metadata": {}, "cell_type": "markdown", "source": "These two classes are the poles of static-file caching. `StaticNoCache` makes the browser revalidate on every use: always fresh at the cost of a conditional request each time, right for files that change under a stable URL (and for dev, where you want edits visible on reload). `StaticImmutable` promises the URL's content will never change, so the browser may cache it forever with no requests at all: only safe when a changed file gets a changed URL, which is what `vurl` or a bundler's content-hashed filenames provide.", - "id": "70c4f465f1a1e4d9" + "id": "2f02fd044b7e6f7c" }, { "metadata": {}, @@ -3962,7 +3962,7 @@ "test_eq(stat_cli.get('/nc/app.css').headers['cache-control'], 'no-cache')\n", "test_eq(stat_cli.get('/imm/app.css').headers['cache-control'], 'public, max-age=31536000, immutable')" ], - "id": "78397e0f041db120" + "id": "a5aca5ab0053e480" }, { "metadata": {}, @@ -3981,13 +3981,13 @@ " q = f'{u.query}&' if u.query else ''\n", " return urlunsplit(u._replace(query=f'{q}v={_vhash(p)}'))\n" ], - "id": "91e627079c83160d" + "id": "374016a0f9b1fd8f" }, { "metadata": {}, "cell_type": "markdown", "source": "Browsers use the URL as the cache key, so a URL that changes whenever the file's contents change can be cached forever: serve the mount with `StaticImmutable` and the asset costs no requests at all until it is next edited. This is the query-param version of the content-hashed filenames that asset pipelines and bundlers produce, without the build step. The hash is cached via `flexicache` with `mtime_policy`, so a call costs one `stat` and the file is only re-read after it changes. The param is inert under `no-cache` serving, so the same links work in dev with `StaticNoCache`, where the file is rechecked on each reload.", - "id": "bc9f863ad8101d60" + "id": "2ef4d5521decc854" }, { "metadata": {}, @@ -4007,7 +4007,7 @@ "os.utime(tmp/'a.css', (time.time()+1,)*2)\n", "assert vurl('a.css', tmp) != u" ], - "id": "35c4396c812bdbbb" + "id": "486e33ec58e33f6f" }, { "metadata": {}, @@ -4019,7 +4019,7 @@ "from functools import wraps\n", "from inspect import signature, isawaitable" ], - "id": "e77d8aa644feefcd" + "id": "8c63143a26a88d2b" }, { "metadata": {}, @@ -4038,7 +4038,7 @@ " f.__annotations__[name] = typ\n", " return f" ], - "id": "97d0447b3fe8d090" + "id": "3fe02cd26e9372c8" }, { "metadata": {}, @@ -4068,19 +4068,19 @@ " add_sig_param(_inner, k, anno, default=p.default)\n", " return _inner" ], - "id": "d9d0b14c50a4ee20" + "id": "32741e75dc3e7738" }, { "metadata": {}, "cell_type": "markdown", "source": "`into` is a decorator that composes two functions: the decorated route function and an outer \"wrapper\" function (like a layout). The route's return value is passed as positional args to the wrapper. Any keyword parameters listed in `params` are added to the route's signature, so they become available as query/form parameters. This lets you write simple routes that return just their content, while the layout and its parameters are handled automatically.", - "id": "170d28cff6e4799a" + "id": "d9b63b093a275569" }, { "metadata": {}, "cell_type": "markdown", "source": "Here `hello` returns a single `P` tag, but `into(my_layout)` passes it into `my_layout`, which wraps it in a `Titled`. The `title` parameter is injected into `hello`'s signature so it can be set via query params.", - "id": "da98f752664d3c67" + "id": "17228f0b1e481002" }, { "metadata": {}, @@ -4096,13 +4096,13 @@ "@into(my_layout)\n", "def hello(name:str='World'): return P(f'Hello, {name}!')" ], - "id": "ef603fee8f8e74f9" + "id": "4fd55d8c8aa07481" }, { "metadata": {}, "cell_type": "markdown", "source": "With no query params, `name` defaults to `'World'` and `title` defaults to `'Default'` (from `my_layout`'s own default), giving us a page titled \"Default\" containing \"Hello, World!\".", - "id": "c9e190baca5d582c" + "id": "bb0ee26d1667e259" }, { "metadata": {}, @@ -4114,13 +4114,13 @@ "assert 'Default' in r.text\n", "assert '

Hello, World!

' in r.text" ], - "id": "af10b39dcbaf6fcf" + "id": "d628bc42184b7313" }, { "metadata": {}, "cell_type": "markdown", "source": "Here, both `name` and `title` are provided as query params. `name='Jeremy'` is handled by `hello` directly, while `title='Greetings'` is the injected param that gets forwarded to `my_layout`.", - "id": "dc4f32eee6a84a4" + "id": "ccd09b2154990ebb" }, { "metadata": {}, @@ -4132,7 +4132,7 @@ "assert 'Greetings' in r.text\n", "assert '

Hello, Jeremy!

' in r.text" ], - "id": "9b9ac10381a145ae" + "id": "32a8e802e0ddc7d3" }, { "metadata": {}, @@ -4148,7 +4148,7 @@ " await self._app(scope, receive, send)\n", " " ], - "id": "7a5ebb738f694d75" + "id": "204806dce2db3c7" }, { "metadata": {}, @@ -4171,7 +4171,7 @@ " headers = {**(self.headers or {}), **httphdrs}\n", " return self.cls(cts, status_code=self.status_code, headers=headers, media_type=self.media_type, background=tasks)" ], - "id": "41b3a970fb0d5b7c" + "id": "d6f4e6547207c467" }, { "metadata": {}, @@ -4191,13 +4191,13 @@ "txt = r.text\n", "assert 'Foo' in txt and '

bar

' in txt and '' in txt" ], - "id": "4bd5d1f492918b6a" + "id": "58fd0fb735784994" }, { "metadata": {}, "cell_type": "markdown", "source": "Test on a single background task:", - "id": "6df76d2a9608cbdc" + "id": "255ca8560b1f7a72" }, { "metadata": {}, @@ -4218,13 +4218,13 @@ "test_eq(r.status_code, 200)\n", "\n" ], - "id": "d08eb5f58af30580" + "id": "4ee096c361ce0e8e" }, { "metadata": {}, "cell_type": "markdown", "source": "Test multiple background tasks:", - "id": "99c9fd088ff2c315" + "id": "bafb0ae46c2c25db" }, { "metadata": {}, @@ -4238,7 +4238,7 @@ " time.sleep(amount)\n", " print(f'Slept for {amount}s') " ], - "id": "a5502eff873e0492" + "id": "f3eea23bbaa3b111" }, { "metadata": {}, @@ -4255,7 +4255,7 @@ "r = cli.get('/backgrounds')\n", "test_eq(r.status_code, 200)" ], - "id": "1536be70e3244b35" + "id": "f5f8db320d2f93f1" }, { "metadata": {}, @@ -4271,7 +4271,7 @@ "r = cli.get('/backgrounds2')\n", "test_eq(r.status_code, 200)" ], - "id": "d4bca91cd874fc15" + "id": "15621d1cbcc6cd5d" }, { "metadata": {}, @@ -4288,7 +4288,7 @@ "test_eq(r.status_code, 200)\n", "r.json()" ], - "id": "e20e7c963bf0e8d3" + "id": "58849b9e0df97f10" }, { "metadata": {}, @@ -4303,7 +4303,7 @@ " res = b64encode(id4.bytes)\n", " return '_' + res.decode().rstrip('=').translate(str.maketrans('+/', '_-'))" ], - "id": "eabef5efb84fbbce" + "id": "cdd6ad44c38a4b4f" }, { "metadata": {}, @@ -4317,7 +4317,7 @@ " if not getattr(s, 'id', None): s.id = unqid()\n", " for c in s.children: _add_ids(c)" ], - "id": "7b02ac1afad917b7" + "id": "d4e9bf553babebff" }, { "metadata": {}, @@ -4337,7 +4337,7 @@ " app._send = send\n", " return send" ], - "id": "3214911e487f8536" + "id": "e3bc86255a535e1c" }, { "metadata": {}, @@ -4355,7 +4355,7 @@ " @self.route(devtools_loc)\n", " def devtools(): return dict(workspace=dict(root=str(path), uuid=uuid))" ], - "id": "9b073cb96670c884" + "id": "47f0ccef326ca8bb" }, { "metadata": {}, @@ -4375,7 +4375,7 @@ " client.cookies.update({self.session_cookie: data.decode()})\n", " return client" ], - "id": "d9fc5093f40be209" + "id": "3c34070a261296c0" }, { "metadata": {}, @@ -4391,7 +4391,7 @@ " unsigned = itsdangerous.TimestampSigner(self.secret_key).unsign(cookie, max_age=None)\n", " return loads(b64decode(unsigned).decode())" ], - "id": "da949a3f6dd16b6c" + "id": "abd39a12bd55fe96" }, { "metadata": {}, @@ -4414,7 +4414,7 @@ "\n", " return FastHTMLTestClient(self, cookies=self.get_client(**kw).cookies)" ], - "id": "a631620ade78cb51" + "id": "51b3a040004e2391" }, { "metadata": {}, @@ -4425,13 +4425,13 @@ "cli = app.get_testclient(auth='user1')\n", "test_eq(cli.session['auth'], 'user1')" ], - "id": "9a572b597b4142d6" + "id": "179a77ec36787faa" }, { "metadata": {}, "cell_type": "markdown", "source": "## Export -", - "id": "87aff436308386ab" + "id": "b41ade09c8f11e7" }, { "metadata": {}, @@ -4443,7 +4443,7 @@ "import nbdev\n", "nbdev.nbdev_export()" ], - "id": "8e4a52eca26ad422" + "id": "b2495577cf248660" } ], "metadata": { From 62a665d2fedcb23f8f4ecebcdcd665a100cedb21 Mon Sep 17 00:00:00 2001 From: Renato Gomes Damas Date: Wed, 21 Oct 2026 11:48:54 -0300 Subject: [PATCH 13/14] refactor: improve request parameter handling and update documentation --- fasthtml/core.py | 228 ++-- nbs/api/00_core.ipynb | 2366 ++++++++++++++++++++++------------------- 2 files changed, 1359 insertions(+), 1235 deletions(-) diff --git a/fasthtml/core.py b/fasthtml/core.py index 894096cb..2278ddce 100644 --- a/fasthtml/core.py +++ b/fasthtml/core.py @@ -18,7 +18,7 @@ class Cards: ... # class route group: each verb-named method (get, patch, . Handlers return FT trees (from `fastcore.xml`), rendered as HTML automatically: a full page for regular requests, a bare fragment for HTMX requests. In a full page, top-level `Title`, `Meta`, `Link`, and `Style` items go in ``; the rest goes in ``. Strings are sent as HTML, dicts as JSON, and a Starlette `Response` is sent untouched. A return tuple may mix content with special items: any `HttpHeader` (e.g. from `cookie()` or `HtmxResponseHeaders()`) becomes a response header, any `BackgroundTask` runs after the response is sent, and the rest renders as content. `Redirect` picks the right redirect mechanism for HTMX vs regular requests, and `FtResponse` wraps FT content when you need the status code or headers. -Handler parameters are filled from the request: each is looked up in path, cookie, header (snake_case names match Hyphen-Case headers), query, then form data (use `Annotated[T, Alias('name')]` to read a different request name), and cast by calling its annotation on the value. Hyphens in form/query names match underscores in handler parameters and typed body fields. Exact names take precedence within each source. Dictionary and request access retain the original keys. `bool`, `int`, and `date` get smart string parsing; `UploadFile` passes through. Repeated params take the last value unless annotated `list[T]`, which collects them all. A param with no annotation and no special name is ignored, with a warning. A dataclass, TypedDict, namedtuple, or any annotated class collects the whole form body; a `__from_request__` classmethod customizes construction. A missing required param is a 400, a failed cast a 404. These special names need no annotation: +Handler parameters are filled from the request: each is looked up in path, cookie, header (snake_case names match Hyphen-Case headers), query, then form data, and cast by calling its annotation on the value. Hyphens in form/query names match underscores in handler parameters and typed body fields. To read a different request name, use `Annotated[T, Alias('name')]`. Exact names take precedence within each source. Dictionary and request access retain the original keys. `bool`, `int`, and `date` get smart string parsing; `UploadFile` passes through. Repeated params take the last value unless annotated `list[T]`, which collects them all. A param with no annotation and no special name is ignored, with a warning. A dataclass, TypedDict, namedtuple, or any annotated class collects the whole form body; a `__from_request__` classmethod customizes construction. A missing required param is a 400, a failed cast a 404. These special names need no annotation: req, ws the Request / WebSocket connection sess session dict @@ -54,7 +54,7 @@ class Cards: ... # class route group: each verb-named method (get, patch, . 'RouteFuncs', 'APIRouter', 'cookie', 'reg_re_param', 'StaticNoCache', 'StaticImmutable', 'vurl', 'add_sig_param', 'into', 'MiddlewareBase', 'FtResponse', 'unqid'] -# %% ../nbs/api/00_core.ipynb #23503b9e +# %% ../nbs/api/00_core.ipynb #b7a14a169b3297a0 import json,uuid,inspect,types,asyncio,inspect,random,contextlib,itsdangerous,hashlib,signal,subprocess from uuid import uuid5, NAMESPACE_URL @@ -82,23 +82,23 @@ class Cards: ... # class route group: each verb-named method (get, patch, . from .starlette import * from python_multipart.exceptions import MultipartParseError -# %% ../nbs/api/00_core.ipynb #19d3f2a7 +# %% ../nbs/api/00_core.ipynb #1585be45cd347d8d def _params(f): return signature_ex(f, True).parameters empty = Parameter.empty -# %% ../nbs/api/00_core.ipynb #e68a76c9 +# %% ../nbs/api/00_core.ipynb #aecb7676f7cc2369 def parsed_date(s:str): "Convert `s` to a datetime" return dtparse.parse(s) -# %% ../nbs/api/00_core.ipynb #7c820373 +# %% ../nbs/api/00_core.ipynb #8615d8ef40e50851 def snake2hyphens(s:str): "Convert `s` from snake case to hyphenated and capitalised" s = snake2camel(s) return camel2words(s, '-') -# %% ../nbs/api/00_core.ipynb #25f3b8f8 +# %% ../nbs/api/00_core.ipynb #81ad0c31c5e60260 htmx_hdrs = dict( boosted="HX-Boosted", current_url="HX-Current-URL", @@ -123,13 +123,13 @@ def _get_htmx(h): res = {k:h.get(v.lower(), None) for k,v in htmx_hdrs.items()} return HtmxHeaders(**res) -# %% ../nbs/api/00_core.ipynb #1d53e8e7 +# %% ../nbs/api/00_core.ipynb #49368755a70898a0 def _mk_list(t, v): return [t(o) for o in listify(v)] -# %% ../nbs/api/00_core.ipynb #5ab74473 +# %% ../nbs/api/00_core.ipynb #58685ffc8373ba6f fh_cfg = AttrDict(indent=True) -# %% ../nbs/api/00_core.ipynb #88d12e68 +# %% ../nbs/api/00_core.ipynb #287965806fac1332 _special_names = {'ws','request','session','scope','data','htmx','app','state','auth','send','api','body','hdrs','ftrs','bodykw','htmlkw','resp','self'} def _check_anno(arg, anno): @@ -137,7 +137,7 @@ def _check_anno(arg, anno): if anno is empty and arg.lower() not in _special_names and not any(s.startswith(arg.lower()) for s in ('request','session')): return f"`{arg}` has no type annotation and is not a recognised special name, so is ignored." if isinstance(anno, type) and not get_origin(anno) and issubclass(anno, (list, tuple)) and not _is_body(anno): return f"`{arg}` uses bare `{anno.__name__}` annotation, so is ignored (use e.g. `{anno.__name__}[str]` instead)." -# %% ../nbs/api/00_core.ipynb #0afb520c +# %% ../nbs/api/00_core.ipynb #e0ed6b4ddd1014c1 def _fix_anno(t, o): "Create appropriate callable type for casting a `str` to type `t` (or first type in `t` if union)" origin = get_origin(t) @@ -150,7 +150,7 @@ def _fix_anno(t, o): if not isinstance(o, (str,list,tuple)): return o return res(o[-1]) if isinstance(o,(list,tuple)) else res(o) -# %% ../nbs/api/00_core.ipynb #c58ccadb +# %% ../nbs/api/00_core.ipynb #3b51bbad3c65426 def _form_arg(k, v, d): "Get type by accessing key `k` from `d`, and use to cast `v`" if v is None: return @@ -160,35 +160,35 @@ def _form_arg(k, v, d): if not anno: return v return _fix_anno(anno, v) -# %% ../nbs/api/00_core.ipynb #5fc04751 +# %% ../nbs/api/00_core.ipynb #55342e74abb8a521 @dataclass class HttpHeader: "A response header as a k,v pair" k:str;v:str -# %% ../nbs/api/00_core.ipynb #94e18161 +# %% ../nbs/api/00_core.ipynb #4e1a41ff0d2006f8 def _to_htmx_header(s): return 'HX-' + s.replace('_', '-').title() htmx_resps = dict(location=None, push_url=None, redirect=None, refresh=None, replace_url=None, reswap=None, retarget=None, reselect=None, trigger=None, trigger_after_settle=None, trigger_after_swap=None) -# %% ../nbs/api/00_core.ipynb #f6a2e62e +# %% ../nbs/api/00_core.ipynb #1bcf3e6bbeb82969 @use_kwargs_dict(**htmx_resps) def HtmxResponseHeaders(**kwargs): "HTMX response headers" res = tuple(HttpHeader(_to_htmx_header(k), v) for k,v in kwargs.items()) return res[0] if len(res)==1 else res -# %% ../nbs/api/00_core.ipynb #56cc589f +# %% ../nbs/api/00_core.ipynb #9efb05e73d5f5947 def _annotations(anno): "Same as `get_annotations`, but also works on namedtuples" if is_namedtuple(anno): return {o:str for o in anno._fields} return get_annotations(anno) -# %% ../nbs/api/00_core.ipynb #cb4ed4aa +# %% ../nbs/api/00_core.ipynb #e5828b2e7682c383 def _is_body(anno): return issubclass(anno, (dict,ns)) or hasattr(anno,'__from_request__') or _annotations(anno) -# %% ../nbs/api/00_core.ipynb #ffdde66f +# %% ../nbs/api/00_core.ipynb #a3058a8b3943fd8d def _formitem(form, k): "Return item `k`, accepting hyphens for underscores and unwrapping single-item form lists" if k not in form: k = {o.replace('-', '_'):o for o in form}.get(k, k) @@ -196,16 +196,16 @@ def _formitem(form, k): o = form.getlist(k) return o[0] if len(o) == 1 else o if o else None -# %% ../nbs/api/00_core.ipynb #5fe74444 +# %% ../nbs/api/00_core.ipynb #3c3233e509f6970e def form2dict(form: FormData) -> dict: "Convert starlette form data to a dict" if isinstance(form, dict): return form return {k: _formitem(form, k) for k in form} -# %% ../nbs/api/00_core.ipynb #8899bc0a +# %% ../nbs/api/00_core.ipynb #da31ece677242cc6 DEF_MAXPART = 100*1024*1024 -# %% ../nbs/api/00_core.ipynb #42c9cea0 +# %% ../nbs/api/00_core.ipynb #73947311e8867ddf async def parse_form(req: Request) -> FormData: "Starlette errors on empty multipart/json forms and 500s on malformed multipart, so this handles those situations" ctype = req.headers.get("Content-Type", "") @@ -224,7 +224,7 @@ async def parse_form(req: Request) -> FormData: return res return await req.form(max_part_size=maxpart) -# %% ../nbs/api/00_core.ipynb #0caedd04 +# %% ../nbs/api/00_core.ipynb #e80f45b5f2d1c328 async def _from_body(conn, p, data): "Create an instance of the annotated type from pre-parsed `data`" anno = p.annotation @@ -240,7 +240,7 @@ async def _from_body(conn, p, data): cargs = {k: _form_arg(k, v, d) for k, v in data.items() if not d or k in d} return anno(**cargs) -# %% ../nbs/api/00_core.ipynb #88b6da3f +# %% ../nbs/api/00_core.ipynb #eb20d63ddb8c94ef class ApiReturn: "Request param: call with browser and API responses; returns kwargs as JSON if the client accepts `application/json`, else `norm`" @classmethod @@ -249,7 +249,7 @@ def __init__(self, isapi=False): self.isapi = isapi def __call__(self, norm=None, **kw): return kw if self.isapi else norm def __bool__(self): return bool(self.isapi) -# %% ../nbs/api/00_core.ipynb #7cc39ba9 +# %% ../nbs/api/00_core.ipynb #61ac79f78f6492d6 class JSONResponse(JSONResponseOrig): "Same as starlette's version, but auto-stringifies non serializable types" def render(self, content:Any)->bytes: @@ -258,7 +258,7 @@ def _default(o): return list(o) if is_listy(o) else str(o) return res.encode("utf-8") -# %% ../nbs/api/00_core.ipynb #5fa96e3a +# %% ../nbs/api/00_core.ipynb #4d46f096ae3f0e05 @dataclass(frozen=True) class Alias: "Read a handler param from request data under `name` instead of its Python name, e.g. `Annotated[str, Alias('user-id')]`" @@ -283,28 +283,28 @@ async def _find_p(conn, data, hdrs, arg:str, p:Parameter): if _is_body(anno): if 'session'.startswith(key.lower()): return conn.scope.get('session', {}) return await _from_body(conn, p, data) - if (msg := _check_anno(arg, anno)): return warn(msg) + if (msg := _check_anno(key, anno)): return warn(msg) # Special param names with no annotations if anno is empty: - if arg.lower()=='ws' or 'request'.startswith(arg.lower()): return conn - if 'session'.startswith(arg.lower()): return conn.scope.get('session', {}) - if arg.lower()=='scope': return conn.scope - if arg.lower()=='data': return data - if arg.lower()=='htmx': return _get_htmx(hdrs) - if arg.lower()=='app': return conn.scope['app'] - if arg.lower()=='state': return conn.scope['app'].state - if arg.lower()=='auth': return conn.scope.get('auth', None) - if arg.lower()=='send': + if key.lower()=='ws' or 'request'.startswith(key.lower()): return conn + if 'session'.startswith(key.lower()): return conn.scope.get('session', {}) + if key.lower()=='scope': return conn.scope + if key.lower()=='data': return data + if key.lower()=='htmx': return _get_htmx(hdrs) + if key.lower()=='app': return conn.scope['app'] + if key.lower()=='state': return conn.scope['app'].state + if key.lower()=='auth': return conn.scope.get('auth', None) + if key.lower()=='send': assert not isinstance(conn, Request), "`send` requires a websocket, not a `Request`" return partial(_send_ws, conn) - if arg.lower()=='api': return ApiReturn(hdrs.get('accept')=='application/json') - if arg.lower()=='body': return (await conn.body()).decode() - if arg.lower() in ('hdrs','ftrs','bodykw','htmlkw'): return getattr(conn, arg.lower()) + if key.lower()=='api': return ApiReturn(hdrs.get('accept')=='application/json') + if key.lower()=='body': return (await conn.body()).decode() + if key.lower() in ('hdrs','ftrs','bodykw','htmlkw'): return getattr(conn, key.lower()) return None # Not a special name or a special annotation res = conn.path_params.get(key, None) if res in (empty,None): res = conn.cookies.get(key, None) - if res in (empty,None): res = hdrs.get(alias or snake2hyphens(key), None) + if res in (empty,None): res = hdrs.get(snake2hyphens(key), None) if res in (empty,None): res = _formitem(conn.query_params, key) if res in (empty,None): res = _formitem(data, key) if res in (empty,None) and isinstance(vals := data.get('values'), dict): res = _formitem(vals, key) # htmx v4 nests form data under `values` @@ -318,17 +318,17 @@ async def _find_p(conn, data, hdrs, arg:str, p:Parameter): if isinstance(conn, Request): raise HTTPException(404, f"{conn.url.path}: {e}") from None raise -# %% ../nbs/api/00_core.ipynb #bf42edad +# %% ../nbs/api/00_core.ipynb #5849a37703c71c4b async def _find_ps(conn, data, hdrs, params): if conn.query_params: data |= dict(conn.query_params) return {arg:await _find_p(conn, data, hdrs, arg, p) for arg,p in params.items()} -# %% ../nbs/api/00_core.ipynb #090f1f0f +# %% ../nbs/api/00_core.ipynb #b4a0893dd0cac34a async def _wrap_req(req, params): data = form2dict(await parse_form(req)) return await _find_ps(req, data, req.headers, params) -# %% ../nbs/api/00_core.ipynb #7a661bfa +# %% ../nbs/api/00_core.ipynb #4b264f3ec9a80e3a def flat_xt(lst): "Flatten lists" result = [] @@ -338,23 +338,23 @@ def flat_xt(lst): else: result.append(item) return tuple(result) -# %% ../nbs/api/00_core.ipynb #aacff5ac +# %% ../nbs/api/00_core.ipynb #4b57d3d58af69e51 class Beforeware: "Wrap a `before` function with `skip` path patterns that bypass it" def __init__(self, f, skip=None): self.f,self.skip = f,skip or [] def __repr__(self): return f'Beforeware({self.f}, skip={self.skip})' -# %% ../nbs/api/00_core.ipynb #78c3c357 +# %% ../nbs/api/00_core.ipynb #de37dcd7b5641749 async def _handle(f, /, *args, **kwargs): return (await f(*args, **kwargs)) if is_async_callable(f) else await run_in_threadpool(f, *args, **kwargs) -# %% ../nbs/api/00_core.ipynb #ad0f0e87 +# %% ../nbs/api/00_core.ipynb #761597782f7f9df6 async def _wrap_ws(ws, data, params): raw = data.pop('HEADERS', {}) or (data.pop('headers') if isinstance(data.get('headers'), dict) else {}) # htmx v4 sends lowercase `headers` hdrs = Headers({k.lower():v for k,v in raw.items() if v is not None}) return await _find_ps(ws, data, hdrs, params) -# %% ../nbs/api/00_core.ipynb #dcc15129 +# %% ../nbs/api/00_core.ipynb #7a3be2b2f30770d7 async def _send_ws(ws, resp): if not resp: return res = to_xml(resp, indent=fh_cfg.indent) @@ -382,12 +382,12 @@ async def _recv(self, ws, data): await _generic_handler(recv, ws, data) cls.on_receive = _recv return cls -# %% ../nbs/api/00_core.ipynb #5b0e7677 +# %% ../nbs/api/00_core.ipynb #ddc64ff604c831b8 def EventStream(s): "Create a text/event-stream response from `s`" return StreamingResponse(s, media_type="text/event-stream") -# %% ../nbs/api/00_core.ipynb #0dd0a414 +# %% ../nbs/api/00_core.ipynb #2e11648d17d6d6f5 def signal_shutdown(): "Return an `asyncio.Event` set when uvicorn receives a shutdown signal" from uvicorn.main import Server @@ -399,21 +399,21 @@ def handle_exit(self:Server, *args, **kwargs): self._orig_handle_exit(*args, **kwargs) return event -# %% ../nbs/api/00_core.ipynb #03f4c639 +# %% ../nbs/api/00_core.ipynb #f660c44ff209b90c def uri(_arg, **kwargs): "Create a URI by URL-encoding `_arg` and appending query parameters from `kwargs`" return f"{quote(_arg)}/{urlencode(kwargs, doseq=True)}" -# %% ../nbs/api/00_core.ipynb #bdb2ac14 +# %% ../nbs/api/00_core.ipynb #3e45f287f5af27c5 def decode_uri(s): "Decode a URI created by `uri()` back into argument and keyword dict" arg,_,kw = s.partition('/') return unquote(arg), {k:v[0] for k,v in parse_qs(kw).items()} -# %% ../nbs/api/00_core.ipynb #b80ce139 +# %% ../nbs/api/00_core.ipynb #580afa399f3bd333 from starlette.convertors import StringConvertor -# %% ../nbs/api/00_core.ipynb #a27adc1e +# %% ../nbs/api/00_core.ipynb #2bb9a1ff5768ba68 StringConvertor.regex = "[^/]*" # `+` replaced with `*` @patch @@ -423,13 +423,13 @@ def to_string(self:StringConvertor, value: str) -> str: # assert value, "Must not be empty" # line removed due to errors return value -# %% ../nbs/api/00_core.ipynb #46614165 +# %% ../nbs/api/00_core.ipynb #d99b78e3a99c3ec0 @patch def url_path_for(self:HTTPConnection, name: str, **path_params): lp = self.scope['app'].url_path_for(name, **path_params) return URLPath(f"{self.scope['root_path']}{lp}", lp.protocol, lp.host) -# %% ../nbs/api/00_core.ipynb #c1707d59 +# %% ../nbs/api/00_core.ipynb #c4d78aa8d576e6cc _verbs = dict(get='hx-get', post='hx-post', put='hx-put', delete='hx-delete', patch='hx-patch', link='href') def _url_for(req, t): @@ -455,10 +455,10 @@ def _to_xml(req, resp, indent): _find_targets(req, resp) return to_xml(resp, indent=indent) -# %% ../nbs/api/00_core.ipynb #f1e3ed2d +# %% ../nbs/api/00_core.ipynb #f2f473dc3aa8e232 _iter_typs = (tuple,list,map,filter,range,types.GeneratorType) -# %% ../nbs/api/00_core.ipynb #a407dc0e +# %% ../nbs/api/00_core.ipynb #ce31ff717114b811 def flat_tuple(o): "Flatten nested iterables into a single tuple" result = [] @@ -469,12 +469,12 @@ def flat_tuple(o): else: result.append(item) return tuple(result) -# %% ../nbs/api/00_core.ipynb #d36402e6 +# %% ../nbs/api/00_core.ipynb #aaf0c02fc0142c20 def noop_body(c, req): "Default Body wrap function which just returns the content" return c -# %% ../nbs/api/00_core.ipynb #7f49728d +# %% ../nbs/api/00_core.ipynb #6df817363734849b def respond(req, heads, bdy): "Default FT response creation function" body_wrap = getattr(req, 'body_wrap', noop_body) @@ -483,13 +483,13 @@ def respond(req, heads, bdy): body = Body(body_wrap(*bw_args), *flat_xt(req.ftrs), **req.bodykw) return Html(Head(*heads, *flat_xt(req.hdrs)), body, **req.htmlkw) -# %% ../nbs/api/00_core.ipynb #b2007479 +# %% ../nbs/api/00_core.ipynb #2f96c17575a317a def is_full_page(req, resp): "Check if response should be rendered as full page or fragment" if resp and any(getattr(o, 'tag', '')=='html' for o in resp): return True return 'hx-request' in req.headers and 'hx-history-restore-request' not in req.headers -# %% ../nbs/api/00_core.ipynb #358badec +# %% ../nbs/api/00_core.ipynb #99a2f618ca8e26e9 def _part_resp(req, resp): "Partition response into HTTP headers, background tasks, and content" resp = flat_tuple(resp) @@ -506,7 +506,7 @@ def _part_resp(req, resp): if len(resp)==1: resp = resp[0] return resp,kw -# %% ../nbs/api/00_core.ipynb #da449a7b +# %% ../nbs/api/00_core.ipynb #d18dc765f6c377c3 def _canonical(req): if not req.app.canonical: return [] url = str(getattr(req, 'canonical', req.url)).replace('http://', 'https://', 1) @@ -522,12 +522,12 @@ def _xt_cts(req, resp): resp = respond(req, [*heads, *title, *_canonical(req)], bdy) return _to_xml(req, resp, indent=fh_cfg.indent) -# %% ../nbs/api/00_core.ipynb #775fb66b +# %% ../nbs/api/00_core.ipynb #5afa1b8942912373 def _is_ft_resp(resp): "Check if response is a FastTag-compatible type" return isinstance(resp, _iter_typs+(HttpHeader,FT)) or hasattr(resp, '__ft__') -# %% ../nbs/api/00_core.ipynb #968d9245 +# %% ../nbs/api/00_core.ipynb #67c986c99e7a6231 def _resp(req, resp, cls=empty, status_code=200): "Create appropriate HTTP response from request and response data" if resp is None: resp='' @@ -547,7 +547,7 @@ def _resp(req, resp, cls=empty, status_code=200): cls = HTMLResponse return cls(resp, status_code=status_code, **kw) -# %% ../nbs/api/00_core.ipynb #eac44461 +# %% ../nbs/api/00_core.ipynb #15e507d2acd3232e class Redirect: "Use HTMX or Starlette RedirectResponse as required to redirect to `loc`" def __init__(self, loc): self.loc = loc @@ -555,13 +555,13 @@ def __response__(self, req): if 'hx-request' in req.headers: return HtmxResponseHeaders(redirect=self.loc) return RedirectResponse(self.loc, status_code=303) -# %% ../nbs/api/00_core.ipynb #1ba52822 +# %% ../nbs/api/00_core.ipynb #92a6fdb45add90f0 async def _wrap_call(f, req, params): "Wrap function call with request parameter injection" wreq = await _wrap_req(req, params) return await _handle(f, **wreq) -# %% ../nbs/api/00_core.ipynb #b0d1cbbf +# %% ../nbs/api/00_core.ipynb #49c3d12b947fa377 # chkstyle: skip htmx_exts = { "morph": "https://cdn.jsdelivr.net/npm/idiomorph@0.7.3/dist/idiomorph-ext.min.js", @@ -581,7 +581,7 @@ async def _wrap_call(f, req, params): "multipart": "https://cdn.jsdelivr.net/npm/htmx.org@4.0.0/dist/ext/hx-multipart.min.js" } -# %% ../nbs/api/00_core.ipynb #60cb52ea +# %% ../nbs/api/00_core.ipynb #b31e24130b390101 htmxsrc = Script(src="https://cdn.jsdelivr.net/npm/htmx.org@2.0.7/dist/htmx.js") htmx4src = Script(src="https://cdn.jsdelivr.net/npm/htmx.org@4.0.0/dist/htmx.min.js") fhjsscr = Script(src="https://cdn.jsdelivr.net/gh/answerdotai/fasthtml-js@1.0.12/fasthtml.js") @@ -590,7 +590,7 @@ async def _wrap_call(f, req, params): viewport = Meta(name="viewport", content="width=device-width, initial-scale=1, viewport-fit=cover") charset = Meta(charset="utf-8") -# %% ../nbs/api/00_core.ipynb #8bd78eeb +# %% ../nbs/api/00_core.ipynb #af5fa00cfaef7a8b def get_key(key=None, fname='.sesskey'): "Get session key from `key` param or read/create from file `fname`" if key: return key @@ -600,12 +600,12 @@ def get_key(key=None, fname='.sesskey'): fname.write_text(key) return key -# %% ../nbs/api/00_core.ipynb #042666e2 +# %% ../nbs/api/00_core.ipynb #17ff3158cc805754 def _list(o): "Wrap non-list item in a list, returning empty list if None" return [] if not o else list(o) if isinstance(o, (tuple,list)) else [o] -# %% ../nbs/api/00_core.ipynb #d276fc71 +# %% ../nbs/api/00_core.ipynb #d2a4061192d883e8 def _wrap_ex(f, status_code, hdrs, ftrs, htmlkw, bodykw, body_wrap): "Wrap exception handler with FastHTML request processing" async def _f(req, exc): @@ -615,7 +615,7 @@ async def _f(req, exc): return _resp(req, res, status_code=status_code) return _f -# %% ../nbs/api/00_core.ipynb #bc323fd4 +# %% ../nbs/api/00_core.ipynb #f0ddf2219c879e3b def qp(p:str, **kw) -> str: "Add parameters kw to path p" def _sub(m): @@ -627,7 +627,7 @@ def _sub(m): # encode query params return p + ('?' + urlencode({k:'' if v in (False,None) else v for k,v in kw.items()},doseq=True) if kw else '') -# %% ../nbs/api/00_core.ipynb #f86690c4 +# %% ../nbs/api/00_core.ipynb #8add43015a5b4c0c def def_hdrs(htmx=True, htmx4=False, surreal=True): "Default headers for a FastHTML app" hdrs = [] @@ -640,7 +640,7 @@ def def_hdrs(htmx=True, htmx4=False, surreal=True): elif htmx: hdrs = [htmxsrc,fhjsscr] + hdrs return [charset, viewport] + hdrs -# %% ../nbs/api/00_core.ipynb #2c5285ae +# %% ../nbs/api/00_core.ipynb #54f3bb368193da5c cors_allow = Middleware(CORSMiddleware, allow_credentials=True, allow_origins=['*'], allow_methods=['*'], allow_headers=['*']) iframe_scr = Script(NotStr(""" @@ -666,7 +666,7 @@ def def_hdrs(htmx=True, htmx4=False, surreal=True): """)) -# %% ../nbs/api/00_core.ipynb #17ced9a3 +# %% ../nbs/api/00_core.ipynb #876c9c8cb63f2cf2 class _LifespanCtx: def __init__(self, gen): self.gen = gen async def __aenter__(self): return await anext(self.gen) @@ -693,7 +693,7 @@ async def _run(self, app): def on_event(self, event_type): return lambda f: (getattr(self, event_type)).append(f) -# %% ../nbs/api/00_core.ipynb #3327a1e9 +# %% ../nbs/api/00_core.ipynb #d8d78a64be4bf27 class FastHTML(Starlette): "An HTML-first Starlette app: handler params filled from the request, FT returns rendered as pages or HTMX fragments" def __init__(self, debug=False, routes=None, middleware=None, title: str = "FastHTML page", exception_handlers=None, @@ -732,7 +732,7 @@ def _not_found(req, exc): return Response('404 Not Found', status_code=404) def on_event(self, event_type): return self.lifespan.on_event(event_type) -# %% ../nbs/api/00_core.ipynb #dce68049 +# %% ../nbs/api/00_core.ipynb #b000f60adf333122 class HostRoute(Route): "Route with optional host-header constraint using Starlette's {param} pattern syntax" def __init__(self, path, endpoint, *, host=None, **kwargs): @@ -750,7 +750,7 @@ def __repr__(self) -> str: methods = sorted(self.methods or []) return f"{self.__class__.__name__}(path={self.path!r}, name={self.name!r}, methods={methods!r}, host={self.host!r})" -# %% ../nbs/api/00_core.ipynb #e0accf76 +# %% ../nbs/api/00_core.ipynb #a1583c0bcb0420f2 @patch def add_route(self:FastHTML, route): "Add or replace a route in the FastHTML app" @@ -762,10 +762,10 @@ def add_route(self:FastHTML, route): self.router.routes.sort(key=lambda r: not getattr(r, 'host', None)) -# %% ../nbs/api/00_core.ipynb #246bd8d1 +# %% ../nbs/api/00_core.ipynb #4917c9f35ccd9f96 all_meths = 'get post put delete patch head trace options'.split() -# %% ../nbs/api/00_core.ipynb #26b147ba +# %% ../nbs/api/00_core.ipynb #46ca67a58ad666b9 @patch def _endp(self:FastHTML, f, body_wrap, before:Optional[Callable|tuple]=None): "Create endpoint wrapper with before/after middleware processing" @@ -794,7 +794,7 @@ async def _f(req): return _resp(req, resp, sig.return_annotation) return _f -# %% ../nbs/api/00_core.ipynb #3818575c +# %% ../nbs/api/00_core.ipynb #a0744b04d81228d6 @patch def _add_ws(self:FastHTML, func, path, conn, disconn, name, middleware): "Add websocket route to FastHTML app" @@ -804,20 +804,20 @@ def _add_ws(self:FastHTML, func, path, conn, disconn, name, middleware): self.add_route(route) return func -# %% ../nbs/api/00_core.ipynb #669e76eb +# %% ../nbs/api/00_core.ipynb #2fc600349ae25291 @patch def ws(self:FastHTML, path:str, conn=None, disconn=None, name=None, middleware=None): "Add a websocket route at `path`" def f(func=noop): return self._add_ws(func, path, conn, disconn, name=name, middleware=middleware) return f -# %% ../nbs/api/00_core.ipynb #j6ete5u68fo +# %% ../nbs/api/00_core.ipynb #17f6217b9e528764 @patch def add_websocket_route(self:FastHTML, path, func, conn=None, disconn=None, name=None, middleware=None): "Add a websocket route at `path` (Starlette-compatible API)" return self._add_ws(func, path, conn, disconn, name=name, middleware=middleware) -# %% ../nbs/api/00_core.ipynb #919618c3 +# %% ../nbs/api/00_core.ipynb #48e0a2670e869b6b def _mk_locfunc(f, p, app=None): "Create a location function wrapper with route path and to() method" class _lf: @@ -831,12 +831,12 @@ def __str__(self): return p return _lf() -# %% ../nbs/api/00_core.ipynb #d2ecc738 +# %% ../nbs/api/00_core.ipynb #a0c09d4bddc479a def nested_name(f): "Get name of function `f` using '_' to join nested function names" return f.__qualname__.replace('..', '_') -# %% ../nbs/api/00_core.ipynb #daafe4fc +# %% ../nbs/api/00_core.ipynb #8f0115f7adff7835 @patch def _add_routes(self:FastHTML, cls, path, methods, name, include_in_schema, body_wrap, host=None, before:Optional[Callable|tuple]=None): "Add HTTP routes from methods on endpoint class `cls`" @@ -848,7 +848,7 @@ def _add_routes(self:FastHTML, cls, path, methods, name, include_in_schema, body if handler: self._add_route(handler, path, meth, name, include_in_schema, body_wrap, host=host, before=before) return lf -# %% ../nbs/api/00_core.ipynb #3710e48b +# %% ../nbs/api/00_core.ipynb #329e78f5bbc6ded1 def _route_pn(func, path, name): "Infer route name/function name/path from an endpoint or endpoint class" fn = nested_name(func) @@ -873,7 +873,7 @@ def _add_route(self:FastHTML, func, path, methods, name, include_in_schema, body lf.__routename__ = n return lf -# %% ../nbs/api/00_core.ipynb #f5cb2c2b +# %% ../nbs/api/00_core.ipynb #ebf0ff44a915aa0c @patch def route(self:FastHTML, path:str=None, methods=None, name=None, include_in_schema=True, body_wrap=None, host=None, before:Optional[Callable|tuple]=None): "Add a route at `path`" @@ -883,14 +883,14 @@ def f(func): for o in all_meths: setattr(FastHTML, o, partialmethod(FastHTML.route, methods=o)) -# %% ../nbs/api/00_core.ipynb #35c35a96 +# %% ../nbs/api/00_core.ipynb #94d6f8f81d93aa5e @patch def set_lifespan(self:FastHTML, value): "Set the lifespan context manager for the FastHTML app" if inspect.isasyncgenfunction(value): value = contextlib.asynccontextmanager(value) self.router.lifespan_context = value -# %% ../nbs/api/00_core.ipynb #3a348474 +# %% ../nbs/api/00_core.ipynb #b5e55224f5a20d18 def serve( appname=None, # Name of the module app='app', # App instance to be served @@ -916,14 +916,14 @@ def serve( print('Link: '+ S.light_red.bold(link)) run(f'{appname}:{app}', host=host, port=port, reload=reload, **kwargs) -# %% ../nbs/api/00_core.ipynb #91b08e9a +# %% ../nbs/api/00_core.ipynb #ddc667c24b6df7dc def _spawn(n): "Run this script `n` times over, numbering each copy in `FH_PROCNUM`, and wait for them all" ps = [subprocess.Popen([sys.executable, *sys.argv], env={**os.environ, 'FH_PROCNUM':str(i)}) for i in range(n)] signal.signal(signal.SIGTERM, lambda *a: [p.terminate() for p in ps]) for p in ps: p.wait() -# %% ../nbs/api/00_core.ipynb #c5220a0e +# %% ../nbs/api/00_core.ipynb #78dc3bffc42b5d1 async def _wait_disconnect(req): while (await req.receive())["type"] != "http.disconnect": pass @@ -938,7 +938,7 @@ async def until_disconnect(req, coro): watch.cancel() if not work.done(): work.cancel() -# %% ../nbs/api/00_core.ipynb #c5721d76 +# %% ../nbs/api/00_core.ipynb #3ddda418760bb472 def cancel_on_disconnect( f=None, # Async route handler to wrap *, @@ -952,7 +952,7 @@ async def _f(__req: Request, *args, **kw): return await (asyncio.wait_for(c, timeout) if timeout is not None else c) return splice_sig(_f, f) -# %% ../nbs/api/00_core.ipynb #8121968a +# %% ../nbs/api/00_core.ipynb #33e9385190411631 class Client: "A simple httpx ASGI client that doesn't require `async`" def __init__(self, app, url="http://testserver"): @@ -965,7 +965,7 @@ async def _request(): return await self.cli.request(method, url, **kwargs) for o in ('get', 'post', 'delete', 'put', 'patch', 'options'): setattr(Client, o, partialmethod(Client._sync, o)) -# %% ../nbs/api/00_core.ipynb #d5223a9a +# %% ../nbs/api/00_core.ipynb #d00984c329331d4 class RouteFuncs: "Attr-access store of named route functions (HTTP verb names excluded)" def __init__(self): super().__setattr__('_funcs', {}) @@ -976,7 +976,7 @@ def __getattr__(self, name): except KeyError: raise AttributeError(f"No route named {name} found in route functions") def __dir__(self): return list(self._funcs.keys()) -# %% ../nbs/api/00_core.ipynb #0f08cb5e +# %% ../nbs/api/00_core.ipynb #55ff40c3aa444235 class APIRouter: "Add routes to an app" def __init__(self, prefix:str|None=None, body_wrap=noop_body): @@ -1016,10 +1016,10 @@ def ws(self, path:str, conn=None, disconn=None, name=None, middleware=None): def f(func=noop): return self.wss.append((func, f"{self.prefix}{path}", conn, disconn, name, middleware)) return f -# %% ../nbs/api/00_core.ipynb #259a0f53 +# %% ../nbs/api/00_core.ipynb #1ea2020dd58c30df for o in all_meths: setattr(APIRouter, o, partialmethod(APIRouter.__call__, methods=o)) -# %% ../nbs/api/00_core.ipynb #e518de83 +# %% ../nbs/api/00_core.ipynb #e645895044c0f961 def cookie(key: str, value="", max_age=None, expires=None, path="/", domain=None, secure=False, httponly=False, samesite="lax",): "Create a 'set-cookie' `HttpHeader`" cookie = cookies.SimpleCookie() @@ -1036,13 +1036,13 @@ def cookie(key: str, value="", max_age=None, expires=None, path="/", domain=None cookie_val = cookie.output(header="").strip() return HttpHeader("set-cookie", cookie_val) -# %% ../nbs/api/00_core.ipynb #8816f277 +# %% ../nbs/api/00_core.ipynb #c094b01b787efa18 def reg_re_param(m, s): "Register a Starlette URL convertor named `m` matching regex `s`" cls = get_class(f'{m}Conv', sup=StringConvertor, regex=s) register_url_convertor(m, cls()) -# %% ../nbs/api/00_core.ipynb #e9535978 +# %% ../nbs/api/00_core.ipynb #6747ee1f8fa10ddb # Starlette doesn't have the '?', so it chomps the whole remaining URL reg_re_param("path", ".*?") _static_exts = "ico gif jpg jpeg webm css js woff png svg mp4 webp ttf otf eot woff2 txt html map pdf zip tgz gz csv mp3 wav ogg flac aac doc docx xls xlsx ppt pptx epub mobi bmp tiff avi mov wmv mkv xml yaml yml rar 7z tar bz2 htm xhtml apk dmg exe msi swf iso".split() @@ -1054,14 +1054,14 @@ def static_route_exts(self:FastHTML, prefix='/', static_path='.', exts='static') @self.get(f"{prefix}{{fname:path}}.{{ext:{exts}}}") async def get(fname:str, ext:str): return FileResponse(f'{static_path}/{fname}.{ext}') -# %% ../nbs/api/00_core.ipynb #b31de65a +# %% ../nbs/api/00_core.ipynb #f821491210017e95 @patch def static_route(self:FastHTML, ext='', prefix='/', static_path='.'): "Add a static route at URL path `prefix` with files from `static_path` and single `ext` (including the '.')" @self.get(f"{prefix}{{fname:path}}{ext}") async def get(fname:str): return FileResponse(f'{static_path}/{fname}{ext}') -# %% ../nbs/api/00_core.ipynb #f63b7a03 +# %% ../nbs/api/00_core.ipynb #392f9abb139bb38f class StaticNoCache(StaticFiles): "StaticFiles that sends `Cache-Control: no-cache`, so browsers revalidate on every use" def file_response(self, *args, **kwargs): @@ -1069,7 +1069,7 @@ def file_response(self, *args, **kwargs): resp.headers.setdefault("Cache-Control", "no-cache") return resp -# %% ../nbs/api/00_core.ipynb #74801f94 +# %% ../nbs/api/00_core.ipynb #a8094de91a8f6335 class StaticImmutable(StaticFiles): "Like `StaticNoCache`, but marks responses as cacheable forever: for versioned URLs such as `vurl` links or content-hashed filenames" def file_response(self, *args, **kwargs): @@ -1077,7 +1077,7 @@ def file_response(self, *args, **kwargs): resp.headers.setdefault("Cache-Control", "public, max-age=31536000, immutable") return resp -# %% ../nbs/api/00_core.ipynb #e38fd6c7 +# %% ../nbs/api/00_core.ipynb #7fffdd2e178e66d9 @flexicache(mtime_policy(arg=0)) def _vhash(p): return hashlib.blake2b(p.read_bytes(), digest_size=4).hexdigest() @@ -1089,11 +1089,11 @@ def vurl(path, root='.'): return urlunsplit(u._replace(query=f'{q}v={_vhash(p)}')) -# %% ../nbs/api/00_core.ipynb #7189daf8 +# %% ../nbs/api/00_core.ipynb #fc3c4a11a7f149ed from functools import wraps from inspect import signature, isawaitable -# %% ../nbs/api/00_core.ipynb #7eed23b7 +# %% ../nbs/api/00_core.ipynb #dcfbe520b21c8a06 def add_sig_param(f, name, typ=NoneType, kind=Parameter.KEYWORD_ONLY, default=Parameter.empty): "Add a parameter to a function's signature" sig = signature(f) @@ -1104,7 +1104,7 @@ def add_sig_param(f, name, typ=NoneType, kind=Parameter.KEYWORD_ONLY, default=Pa f.__annotations__[name] = typ return f -# %% ../nbs/api/00_core.ipynb #9e5a9e88 +# %% ../nbs/api/00_core.ipynb #bc3a2a5a0b908c62 class into: "Decorator to pass a route's return value into `func`, with keyword params added to the route signature" def __init__(self, func): @@ -1126,7 +1126,7 @@ async def _inner(*args, **kw): add_sig_param(_inner, k, anno, default=p.default) return _inner -# %% ../nbs/api/00_core.ipynb #1960d7ff +# %% ../nbs/api/00_core.ipynb #e287be9995e1d974 class MiddlewareBase: "Base for middleware: passes non-http/ws scopes through, else returns the `HTTPConnection`" async def __call__(self, scope, receive, send) -> None: @@ -1134,7 +1134,7 @@ async def __call__(self, scope, receive, send) -> None: await self._app(scope, receive, send) -# %% ../nbs/api/00_core.ipynb #83a20f93 +# %% ../nbs/api/00_core.ipynb #abd3179c8f6dab84 class FtResponse: "Wrap an FT response with any Starlette `Response`" def __init__(self, content, status_code:int=200, headers=None, cls=HTMLResponse, media_type:str|None=None, background: BackgroundTask | None = None): @@ -1149,20 +1149,20 @@ def __response__(self, req): headers = {**(self.headers or {}), **httphdrs} return self.cls(cts, status_code=self.status_code, headers=headers, media_type=self.media_type, background=tasks) -# %% ../nbs/api/00_core.ipynb #9dc1025e +# %% ../nbs/api/00_core.ipynb #7ccb00230cdfb99e def unqid(seeded=False): "Random unique id, base64-encoded and prefixed with '_' so it's usable as an HTML id" id4 = UUID(int=random.getrandbits(128), version=4) if seeded else uuid4() res = b64encode(id4.bytes) return '_' + res.decode().rstrip('=').translate(str.maketrans('+/', '_-')) -# %% ../nbs/api/00_core.ipynb #5b67e014 +# %% ../nbs/api/00_core.ipynb #e70a8dcfe4386a2e def _add_ids(s): if not isinstance(s, FT): return if not getattr(s, 'id', None): s.id = unqid() for c in s.children: _add_ids(c) -# %% ../nbs/api/00_core.ipynb #1f590f25 +# %% ../nbs/api/00_core.ipynb #6a8579524fa4bb56 @patch def setup_ws(app:FastHTML, f=noop): conns = {} @@ -1174,7 +1174,7 @@ async def send(s): app._send = send return send -# %% ../nbs/api/00_core.ipynb #a8a91edd +# %% ../nbs/api/00_core.ipynb #fcb9f273985b611e devtools_loc = "/.well-known/appspecific/com.chrome.devtools.json" @patch @@ -1184,7 +1184,7 @@ def devtools_json(self:FastHTML, path=None, uuid=None): @self.route(devtools_loc) def devtools(): return dict(workspace=dict(root=str(path), uuid=uuid)) -# %% ../nbs/api/00_core.ipynb #e27908c0 +# %% ../nbs/api/00_core.ipynb #3bf9cb548b4906fd @patch def get_client(self:FastHTML, asink=False, **kw): "Get an httpx client with session cookes set from `**kw`" @@ -1196,7 +1196,7 @@ def get_client(self:FastHTML, asink=False, **kw): client.cookies.update({self.session_cookie: data.decode()}) return client -# %% ../nbs/api/00_core.ipynb #c845f437 +# %% ../nbs/api/00_core.ipynb #6942fa7012ca3ec6 @patch def decode_session(self:FastHTML, cookie): "Decode a signed session cookie" @@ -1204,7 +1204,7 @@ def decode_session(self:FastHTML, cookie): unsigned = itsdangerous.TimestampSigner(self.secret_key).unsign(cookie, max_age=None) return loads(b64decode(unsigned).decode()) -# %% ../nbs/api/00_core.ipynb #49260e9b +# %% ../nbs/api/00_core.ipynb #4e64484ff03ceb38 @patch def get_testclient(self:FastHTML, **kw): "Get a Starlette `TestClient` with session cookies set from `**kw`" diff --git a/nbs/api/00_core.ipynb b/nbs/api/00_core.ipynb index 593b44c8..5909f72c 100644 --- a/nbs/api/00_core.ipynb +++ b/nbs/api/00_core.ipynb @@ -1,25 +1,28 @@ { "cells": [ { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, - "source": "#| default_exp core", - "id": "1ec26324bdbbb1c7" + "id": "1ec26324bdbbb1c7", + "metadata": {}, + "outputs": [], + "source": [ + "#| default_exp core" + ] }, { - "metadata": {}, "cell_type": "markdown", + "id": "dedbdfd343c1a82b", + "metadata": {}, "source": [ "# Core\n", "> The `FastHTML` subclass of `Starlette`." - ], - "id": "dedbdfd343c1a82b" + ] }, { - "metadata": {}, "cell_type": "markdown", + "id": "6ee7a67ea3d7ac9c", + "metadata": {}, "source": [ "#| export\n", "Create an app with `app = FastHTML()`. The `@rt` decorator adds routes (`rt = app.route`), inferring what it can from the function:\n", @@ -40,7 +43,7 @@ "\n", "Handlers return FT trees (from `fastcore.xml`), rendered as HTML automatically: a full page for regular requests, a bare fragment for HTMX requests. In a full page, top-level `Title`, `Meta`, `Link`, and `Style` items go in ``; the rest goes in ``. Strings are sent as HTML, dicts as JSON, and a Starlette `Response` is sent untouched. A return tuple may mix content with special items: any `HttpHeader` (e.g. from `cookie()` or `HtmxResponseHeaders()`) becomes a response header, any `BackgroundTask` runs after the response is sent, and the rest renders as content. `Redirect` picks the right redirect mechanism for HTMX vs regular requests, and `FtResponse` wraps FT content when you need the status code or headers.\n", "\n", - "Handler parameters are filled from the request: each is looked up in path, cookie, header (snake_case names match Hyphen-Case headers), query, then form data (use `Annotated[T, Alias('name')]` to read a different request name), and cast by calling its annotation on the value. Hyphens in form/query names match underscores in handler parameters and typed body fields. Exact names take precedence within each source. Dictionary and request access retain the original keys. `bool`, `int`, and `date` get smart string parsing; `UploadFile` passes through. Repeated params take the last value unless annotated `list[T]`, which collects them all. A param with no annotation and no special name is ignored, with a warning. A dataclass, TypedDict, namedtuple, or any annotated class collects the whole form body; a `__from_request__` classmethod customizes construction. A missing required param is a 400, a failed cast a 404. These special names need no annotation:\n", + "Handler parameters are filled from the request: each is looked up in path, cookie, header (snake_case names match Hyphen-Case headers), query, then form data, and cast by calling its annotation on the value. Hyphens in form/query names match underscores in handler parameters and typed body fields. To read a different request name, use `Annotated[T, Alias('name')]`. Exact names take precedence within each source. Dictionary and request access retain the original keys. `bool`, `int`, and `date` get smart string parsing; `UploadFile` passes through. Repeated params take the last value unless annotated `list[T]`, which collects them all. A param with no annotation and no special name is ignored, with a warning. A dataclass, TypedDict, namedtuple, or any annotated class collects the whole form body; a `__from_request__` classmethod customizes construction. A missing required param is a 400, a failed cast a 404. These special names need no annotation:\n", "\n", " req, ws the Request / WebSocket connection\n", " sess session dict\n", @@ -61,26 +64,30 @@ "`before`/`after` functions (app-level, with `Beforeware` skip patterns, or per-route `before=`) get the same param injection as handlers. A `before` returning a value responds with it and skips the handler (the usual auth-guard pattern).\n", "\n", "See the [Handling Handlers tutorial](https://www.fastht.ml/docs/ref/handlers.html.md) for worked examples of the above." - ], - "id": "6ee7a67ea3d7ac9c" + ] }, { - "metadata": {}, "cell_type": "markdown", - "source": "This is the source code to fasthtml. You won't need to read this unless you want to understand how things are built behind the scenes, or need full details of a particular API. The notebook is converted to the Python module [fasthtml/core.py](https://github.com/AnswerDotAI/fasthtml/blob/main/fasthtml/core.py) using [nbdev](https://nbdev.fast.ai/).", - "id": "f4c42f70a7d0b787" + "id": "f4c42f70a7d0b787", + "metadata": {}, + "source": [ + "This is the source code to fasthtml. You won't need to read this unless you want to understand how things are built behind the scenes, or need full details of a particular API. The notebook is converted to the Python module [fasthtml/core.py](https://github.com/AnswerDotAI/fasthtml/blob/main/fasthtml/core.py) using [nbdev](https://nbdev.fast.ai/)." + ] }, { - "metadata": {}, "cell_type": "markdown", - "source": "## Imports and utils", - "id": "db1b60be4448cee7" + "id": "db1b60be4448cee7", + "metadata": {}, + "source": [ + "## Imports and utils" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "b7a14a169b3297a0", + "metadata": {}, + "outputs": [], "source": [ "#| export\n", "import json,uuid,inspect,types,asyncio,inspect,random,contextlib,itsdangerous,hashlib,signal,subprocess\n", @@ -109,14 +116,14 @@ "\n", "from fasthtml.starlette import *\n", "from python_multipart.exceptions import MultipartParseError" - ], - "id": "b7a14a169b3297a0" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "478f6d160ede5f93", + "metadata": {}, + "outputs": [], "source": [ "import time, tempfile\n", "\n", @@ -130,84 +137,92 @@ "from fastcore.test import *\n", "from fastcore.net import run_sync\n", "from starlette.datastructures import UploadFile" - ], - "id": "478f6d160ede5f93" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "1585be45cd347d8d", + "metadata": {}, + "outputs": [], "source": [ "#| export\n", "def _params(f): return signature_ex(f, True).parameters\n", "\n", "empty = Parameter.empty" - ], - "id": "1585be45cd347d8d" + ] }, { - "metadata": {}, "cell_type": "markdown", - "source": "We write source code _first_, and then tests come _after_. The tests serve as both a means to confirm that the code works and also serves as working examples. The first exported function, `parsed_date`, is an example of this pattern.", - "id": "8f4bdd936b68acad" + "id": "8f4bdd936b68acad", + "metadata": {}, + "source": [ + "We write source code _first_, and then tests come _after_. The tests serve as both a means to confirm that the code works and also serves as working examples. The first exported function, `parsed_date`, is an example of this pattern." + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "aecb7676f7cc2369", + "metadata": {}, + "outputs": [], "source": [ "#| export\n", "def parsed_date(s:str):\n", " \"Convert `s` to a datetime\"\n", " return dtparse.parse(s)" - ], - "id": "aecb7676f7cc2369" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, - "source": "parsed_date('2pm')", - "id": "5d987b866e6f7454" + "id": "5d987b866e6f7454", + "metadata": {}, + "outputs": [], + "source": [ + "parsed_date('2pm')" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, - "source": "isinstance(date.fromtimestamp(0), date)", - "id": "ebd59c6831b3cc75" + "id": "ebd59c6831b3cc75", + "metadata": {}, + "outputs": [], + "source": [ + "isinstance(date.fromtimestamp(0), date)" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "8615d8ef40e50851", + "metadata": {}, + "outputs": [], "source": [ "#| export\n", "def snake2hyphens(s:str):\n", " \"Convert `s` from snake case to hyphenated and capitalised\"\n", " s = snake2camel(s)\n", " return camel2words(s, '-')" - ], - "id": "8615d8ef40e50851" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, - "source": "snake2hyphens(\"snake_case\")", - "id": "cac7bfc7b00a30be" + "id": "cac7bfc7b00a30be", + "metadata": {}, + "outputs": [], + "source": [ + "snake2hyphens(\"snake_case\")" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "81ad0c31c5e60260", + "metadata": {}, + "outputs": [], "source": [ "#| export\n", "htmx_hdrs = dict(\n", @@ -233,14 +248,14 @@ "def _get_htmx(h):\n", " res = {k:h.get(v.lower(), None) for k,v in htmx_hdrs.items()}\n", " return HtmxHeaders(**res)" - ], - "id": "81ad0c31c5e60260" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "4ddd28db661e1dba", + "metadata": {}, + "outputs": [], "source": [ "def test_request(url: str='/', headers: dict=None, method: str='get')->Request:\n", " if headers is None: headers={}\n", @@ -248,53 +263,55 @@ " client=('127.0.0.1', 8000), server=('127.0.0.1', 8000))\n", " async def receive(): return dict(type=\"http.request\", body=b\"\", more_body=False)\n", " return Request(scope, receive)" - ], - "id": "4ddd28db661e1dba" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "73f2932151861097", + "metadata": {}, + "outputs": [], "source": [ "h = test_request(headers=Headers({'HX-Request':'1'}))\n", "_get_htmx(h.headers)" - ], - "id": "73f2932151861097" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "49368755a70898a0", + "metadata": {}, + "outputs": [], "source": [ "#| export\n", "def _mk_list(t, v): return [t(o) for o in listify(v)]" - ], - "id": "49368755a70898a0" + ] }, { - "metadata": {}, "cell_type": "markdown", - "source": "## Request and response", - "id": "ca95b6a77993c054" + "id": "ca95b6a77993c054", + "metadata": {}, + "source": [ + "## Request and response" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "58685ffc8373ba6f", + "metadata": {}, + "outputs": [], "source": [ "#| export\n", "fh_cfg = AttrDict(indent=True)" - ], - "id": "58685ffc8373ba6f" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "287965806fac1332", + "metadata": {}, + "outputs": [], "source": [ "#| export\n", "_special_names = {'ws','request','session','scope','data','htmx','app','state','auth','send','api','body','hdrs','ftrs','bodykw','htmlkw','resp','self'}\n", @@ -303,14 +320,14 @@ " \"Check for common annotation issues; returns warning string or None\"\n", " if anno is empty and arg.lower() not in _special_names and not any(s.startswith(arg.lower()) for s in ('request','session')): return f\"`{arg}` has no type annotation and is not a recognised special name, so is ignored.\"\n", " if isinstance(anno, type) and not get_origin(anno) and issubclass(anno, (list, tuple)) and not _is_body(anno): return f\"`{arg}` uses bare `{anno.__name__}` annotation, so is ignored (use e.g. `{anno.__name__}[str]` instead).\"" - ], - "id": "287965806fac1332" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "e0ed6b4ddd1014c1", + "metadata": {}, + "outputs": [], "source": [ "#| export\n", "def _fix_anno(t, o):\n", @@ -324,14 +341,14 @@ " if isinstance(t, type) and issubclass(t, (list,tuple)): return None\n", " if not isinstance(o, (str,list,tuple)): return o\n", " return res(o[-1]) if isinstance(o,(list,tuple)) else res(o)" - ], - "id": "e0ed6b4ddd1014c1" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "be37ef49e13b65d", + "metadata": {}, + "outputs": [], "source": [ "test_eq(_fix_anno(Union[str,None], 'a'), 'a')\n", "test_eq(_fix_anno(float, 0.9), 0.9)\n", @@ -345,14 +362,14 @@ "test_eq(_fix_anno(tuple, ['1','2']), None)\n", "test_eq(_fix_anno(list[str], []), [])\n", "test_eq(_fix_anno(Optional[list[str]], '1'), ['1'])" - ], - "id": "be37ef49e13b65d" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "3b51bbad3c65426", + "metadata": {}, + "outputs": [], "source": [ "#| export\n", "def _form_arg(k, v, d):\n", @@ -363,63 +380,65 @@ " anno = d.get(k, None)\n", " if not anno: return v\n", " return _fix_anno(anno, v)" - ], - "id": "3b51bbad3c65426" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "3e260c670966d74c", + "metadata": {}, + "outputs": [], "source": [ "d = dict(k=int, l=List[int])\n", "test_eq(_form_arg('k', \"1\", d), 1)\n", "test_eq(_form_arg('l', \"1\", d), [1])\n", "test_eq(_form_arg('l', [\"1\",\"2\"], d), [1,2])" - ], - "id": "3e260c670966d74c" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "55342e74abb8a521", + "metadata": {}, + "outputs": [], "source": [ "#| export\n", "@dataclass\n", "class HttpHeader:\n", " \"A response header as a k,v pair\"\n", " k:str;v:str" - ], - "id": "55342e74abb8a521" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "4e1a41ff0d2006f8", + "metadata": {}, + "outputs": [], "source": [ "#| export\n", "def _to_htmx_header(s): return 'HX-' + s.replace('_', '-').title()\n", "\n", "htmx_resps = dict(location=None, push_url=None, redirect=None, refresh=None, replace_url=None,\n", " reswap=None, retarget=None, reselect=None, trigger=None, trigger_after_settle=None, trigger_after_swap=None)" - ], - "id": "4e1a41ff0d2006f8" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, - "source": "_to_htmx_header('trigger_after_settle')", - "id": "3ac6e8a48127c728" + "id": "3ac6e8a48127c728", + "metadata": {}, + "outputs": [], + "source": [ + "_to_htmx_header('trigger_after_settle')" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "1bcf3e6bbeb82969", + "metadata": {}, + "outputs": [], "source": [ "#| export\n", "@use_kwargs_dict(**htmx_resps)\n", @@ -427,70 +446,72 @@ " \"HTMX response headers\"\n", " res = tuple(HttpHeader(_to_htmx_header(k), v) for k,v in kwargs.items())\n", " return res[0] if len(res)==1 else res" - ], - "id": "1bcf3e6bbeb82969" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, - "source": "HtmxResponseHeaders(trigger_after_settle='hi')", - "id": "769922176702c962" + "id": "769922176702c962", + "metadata": {}, + "outputs": [], + "source": [ + "HtmxResponseHeaders(trigger_after_settle='hi')" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "9efb05e73d5f5947", + "metadata": {}, + "outputs": [], "source": [ "#| export\n", "def _annotations(anno):\n", " \"Same as `get_annotations`, but also works on namedtuples\"\n", " if is_namedtuple(anno): return {o:str for o in anno._fields}\n", " return get_annotations(anno)" - ], - "id": "9efb05e73d5f5947" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "6843ecd419c1f999", + "metadata": {}, + "outputs": [], "source": [ "@dataclass\n", "class Foo: a:int; b:str\n", "_annotations(Foo)" - ], - "id": "6843ecd419c1f999" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "7c9b92ae09b4b1ec", + "metadata": {}, + "outputs": [], "source": [ "Point = namedtuple('Point', ['x', 'y'])\n", "_annotations(Point)" - ], - "id": "7c9b92ae09b4b1ec" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "e5828b2e7682c383", + "metadata": {}, + "outputs": [], "source": [ "#| export\n", "def _is_body(anno): return issubclass(anno, (dict,ns)) or hasattr(anno,'__from_request__') or _annotations(anno)" - ], - "id": "e5828b2e7682c383" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "a3058a8b3943fd8d", + "metadata": {}, + "outputs": [], "source": [ "#| export\n", "def _formitem(form, k):\n", @@ -499,53 +520,53 @@ " if isinstance(form, dict): return form.get(k)\n", " o = form.getlist(k)\n", " return o[0] if len(o) == 1 else o if o else None" - ], - "id": "a3058a8b3943fd8d" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "3c3233e509f6970e", + "metadata": {}, + "outputs": [], "source": [ "#| export\n", "def form2dict(form: FormData) -> dict:\n", " \"Convert starlette form data to a dict\"\n", " if isinstance(form, dict): return form\n", " return {k: _formitem(form, k) for k in form}" - ], - "id": "3c3233e509f6970e" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "d5ea2e7798493538", + "metadata": {}, + "outputs": [], "source": [ "d = [('a',1),('a',2),('b',0)]\n", "fd = FormData(d)\n", "res = form2dict(fd)\n", "test_eq(res['a'], [1,2])\n", "test_eq(res['b'], 0)" - ], - "id": "d5ea2e7798493538" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "da31ece677242cc6", + "metadata": {}, + "outputs": [], "source": [ "#| export\n", "DEF_MAXPART = 100*1024*1024" - ], - "id": "da31ece677242cc6" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "73947311e8867ddf", + "metadata": {}, + "outputs": [], "source": [ "#| export\n", "async def parse_form(req: Request) -> FormData:\n", @@ -565,48 +586,50 @@ " if not isinstance(res, dict): raise HTTPException(400, \"JSON body must be an object\")\n", " return res\n", " return await req.form(max_part_size=maxpart)" - ], - "id": "73947311e8867ddf" + ] }, { - "metadata": {}, "cell_type": "markdown", - "source": "Use the special `__from_request__` class method for custom creation:", - "id": "8dc378792d632ae2" + "id": "8dc378792d632ae2", + "metadata": {}, + "source": [ + "Use the special `__from_request__` class method for custom creation:" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "28ed01aae9ac888b", + "metadata": {}, + "outputs": [], "source": [ "class Foo(BasicRepr):\n", " def __init__(self, d): self.d = d\n", "\n", " @classmethod\n", " def __from_request__(cls, data, req): return cls(data)" - ], - "id": "28ed01aae9ac888b" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "91fae17bd4925e81", + "metadata": {}, + "outputs": [], "source": [ "p = Parameter('a', Parameter.POSITIONAL_OR_KEYWORD, annotation=Foo)\n", "\n", "req = test_request(method='POST')\n", "async def mock_form(**kwargs): return FormData({'a':1})\n", "req.form = mock_form" - ], - "id": "91fae17bd4925e81" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "e80f45b5f2d1c328", + "metadata": {}, + "outputs": [], "source": [ "#| export\n", "async def _from_body(conn, p, data):\n", @@ -623,14 +646,14 @@ " if d: data = {k.replace('-', '_'):v for k,v in data.items()} | data\n", " cargs = {k: _form_arg(k, v, d) for k, v in data.items() if not d or k in d}\n", " return anno(**cargs)" - ], - "id": "e80f45b5f2d1c328" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "eb20d63ddb8c94ef", + "metadata": {}, + "outputs": [], "source": [ "#| export\n", "class ApiReturn:\n", @@ -640,20 +663,22 @@ " def __init__(self, isapi=False): self.isapi = isapi\n", " def __call__(self, norm=None, **kw): return kw if self.isapi else norm\n", " def __bool__(self): return bool(self.isapi)" - ], - "id": "eb20d63ddb8c94ef" + ] }, { - "metadata": {}, "cell_type": "markdown", - "source": "Routes often need to return different responses depending on whether the request comes from a browser or an API client. The `api:ApiReturn` parameter handles this automatically — add it to any route signature and call it with two arguments: the API response and the browser response. If the request's `Accept` header is `application/json` then a dict of the kwargs is returned, otherwise, the first value is returned. For example, `return api(Redirect('/records'), id=record.id)` returns {'id':id} for API callers and a redirect for the browser. This keeps your route logic in one place instead of splitting it across separate endpoints.", - "id": "dc6b0adc9f6733b3" + "id": "dc6b0adc9f6733b3", + "metadata": {}, + "source": [ + "Routes often need to return different responses depending on whether the request comes from a browser or an API client. The `api:ApiReturn` parameter handles this automatically — add it to any route signature and call it with two arguments: the API response and the browser response. If the request's `Accept` header is `application/json` then a dict of the kwargs is returned, otherwise, the first value is returned. For example, `return api(Redirect('/records'), id=record.id)` returns {'id':id} for API callers and a redirect for the browser. This keeps your route logic in one place instead of splitting it across separate endpoints." + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "61ac79f78f6492d6", + "metadata": {}, + "outputs": [], "source": [ "#| export\n", "class JSONResponse(JSONResponseOrig):\n", @@ -662,14 +687,14 @@ " def _default(o): return list(o) if is_listy(o) else str(o)\n", " res = json.dumps(content, ensure_ascii=False, allow_nan=False, indent=None, separators=(\",\",\":\"), default=_default)\n", " return res.encode(\"utf-8\")\n" - ], - "id": "61ac79f78f6492d6" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "178e01facf162f65", + "metadata": {}, + "outputs": [], "source": [ "async def f(req):\n", " def _f(p:HttpHeader): ...\n", @@ -683,14 +708,14 @@ "d = dict(k='value1',v=['value2','value3'])\n", "response = client.post('/', data=d)\n", "print(response.json())" - ], - "id": "178e01facf162f65" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "7da5229a3769ed", + "metadata": {}, + "outputs": [], "source": [ "# An empty `application/json` body yields `{}` (like the empty-multipart guard), not a 500\n", "async def _empty_json(req): return JSONResponse(form2dict(await parse_form(req)))\n", @@ -700,65 +725,69 @@ "test_eq(res.json(), {})\n", "res = client.post('/', json={'a':1}) # non-empty json still parses (behavior preserved)\n", "test_eq(res.json(), {'a':1})" - ], - "id": "7da5229a3769ed" + ] }, { - "metadata": {}, "cell_type": "markdown", - "source": "A malformed multipart body (here the opening boundary isn't followed by CRLF) is the client's error, so `parse_form` answers 400 rather than letting the parser's exception surface as a 500:", - "id": "17448e54e1c0f79b" + "id": "17448e54e1c0f79b", + "metadata": {}, + "source": [ + "A malformed multipart body (here the opening boundary isn't followed by CRLF) is the client's error, so `parse_form` answers 400 rather than letting the parser's exception surface as a 500:" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "c53e378d80aef7e5", + "metadata": {}, + "outputs": [], "source": [ "bad = b'--xyzXX\\r\\nContent-Disposition: form-data; name=\"a\"\\r\\n\\r\\n1\\r\\n--xyz--\\r\\n'\n", "res = client.post('/', content=bad, headers={'content-type':'multipart/form-data; boundary=xyz'})\n", "test_eq(res.status_code, 400)\n", "res.text" - ], - "id": "c53e378d80aef7e5" + ] }, { - "metadata": {}, "cell_type": "markdown", - "source": "A JSON body that does not decode, or decodes to something other than an object (an array, say), cannot supply route parameters, so it is refused with 400 rather than failing inside the form conversion:", - "id": "3a468526a5f83f29" + "id": "3a468526a5f83f29", + "metadata": {}, + "source": [ + "A JSON body that does not decode, or decodes to something other than an object (an array, say), cannot supply route parameters, so it is refused with 400 rather than failing inside the form conversion:" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "8e67736be407e8ad", + "metadata": {}, + "outputs": [], "source": [ "res = client.post('/', json=[1,2])\n", "test_eq(res.status_code, 400)\n", "res = client.post('/', content=b'not json', headers={'content-type':'application/json'})\n", "test_eq(res.status_code, 400)\n", "res.text" - ], - "id": "8e67736be407e8ad" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "5a8f91f6d88d1ef4", + "metadata": {}, + "outputs": [], "source": [ "async def f(req): return Response(str(req.query_params.getlist('x')))\n", "client = TestClient(Starlette(routes=[Route('/', f, methods=['GET'])]))\n", "client.get('/?x=1&x=2').text" - ], - "id": "5a8f91f6d88d1ef4" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "4d46f096ae3f0e05", + "metadata": {}, + "outputs": [], "source": [ "#| export\n", "@dataclass(frozen=True)\n", @@ -783,30 +812,30 @@ " if issubclass(anno, State): return conn.scope['app'].state\n", " if anno is dict: return data\n", " if _is_body(anno):\n", - " if 'session'.startswith(arg.lower()): return conn.scope.get('session', {})\n", + " if 'session'.startswith(key.lower()): return conn.scope.get('session', {})\n", " return await _from_body(conn, p, data)\n", - " if (msg := _check_anno(arg, anno)): return warn(msg)\n", + " if (msg := _check_anno(key, anno)): return warn(msg)\n", " # Special param names with no annotations\n", " if anno is empty:\n", - " if arg.lower()=='ws' or 'request'.startswith(arg.lower()): return conn\n", - " if 'session'.startswith(arg.lower()): return conn.scope.get('session', {})\n", - " if arg.lower()=='scope': return conn.scope\n", - " if arg.lower()=='data': return data\n", - " if arg.lower()=='htmx': return _get_htmx(hdrs)\n", - " if arg.lower()=='app': return conn.scope['app']\n", - " if arg.lower()=='state': return conn.scope['app'].state\n", - " if arg.lower()=='auth': return conn.scope.get('auth', None)\n", - " if arg.lower()=='send':\n", + " if key.lower()=='ws' or 'request'.startswith(key.lower()): return conn\n", + " if 'session'.startswith(key.lower()): return conn.scope.get('session', {})\n", + " if key.lower()=='scope': return conn.scope\n", + " if key.lower()=='data': return data\n", + " if key.lower()=='htmx': return _get_htmx(hdrs)\n", + " if key.lower()=='app': return conn.scope['app']\n", + " if key.lower()=='state': return conn.scope['app'].state\n", + " if key.lower()=='auth': return conn.scope.get('auth', None)\n", + " if key.lower()=='send':\n", " assert not isinstance(conn, Request), \"`send` requires a websocket, not a `Request`\"\n", " return partial(_send_ws, conn)\n", - " if arg.lower()=='api': return ApiReturn(hdrs.get('accept')=='application/json')\n", - " if arg.lower()=='body': return (await conn.body()).decode()\n", - " if arg.lower() in ('hdrs','ftrs','bodykw','htmlkw'): return getattr(conn, arg.lower())\n", + " if key.lower()=='api': return ApiReturn(hdrs.get('accept')=='application/json')\n", + " if key.lower()=='body': return (await conn.body()).decode()\n", + " if key.lower() in ('hdrs','ftrs','bodykw','htmlkw'): return getattr(conn, key.lower())\n", " return None\n", " # Not a special name or a special annotation\n", " res = conn.path_params.get(key, None)\n", " if res in (empty,None): res = conn.cookies.get(key, None)\n", - " if res in (empty,None): res = hdrs.get(snake2hyphens(arg), None)\n", + " if res in (empty,None): res = hdrs.get(snake2hyphens(key), None)\n", " if res in (empty,None): res = _formitem(conn.query_params, key)\n", " if res in (empty,None): res = _formitem(data, key)\n", " if res in (empty,None) and isinstance(vals := data.get('values'), dict): res = _formitem(vals, key) # htmx v4 nests form data under `values`\n", @@ -819,51 +848,51 @@ " except ValueError as e:\n", " if isinstance(conn, Request): raise HTTPException(404, f\"{conn.url.path}: {e}\") from None\n", " raise" - ], - "id": "4d46f096ae3f0e05" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "5849a37703c71c4b", + "metadata": {}, + "outputs": [], "source": [ "#| export\n", "async def _find_ps(conn, data, hdrs, params):\n", " if conn.query_params: data |= dict(conn.query_params)\n", " return {arg:await _find_p(conn, data, hdrs, arg, p) for arg,p in params.items()}" - ], - "id": "5849a37703c71c4b" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "d4f32846cec05208", + "metadata": {}, + "outputs": [], "source": [ "data = form2dict(await parse_form(req))\n", "await _from_body(req, p, data)" - ], - "id": "d4f32846cec05208" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "b4a0893dd0cac34a", + "metadata": {}, + "outputs": [], "source": [ "#| export\n", "async def _wrap_req(req, params):\n", " data = form2dict(await parse_form(req))\n", " return await _find_ps(req, data, req.headers, params)" - ], - "id": "b4a0893dd0cac34a" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "29d868c520d765ea", + "metadata": {}, + "outputs": [], "source": [ "def g(test_val:int=0, item:HttpHeader=None, htmx:HtmxHeaders=None, api:ApiReturn=None): ...\n", "\n", @@ -876,14 +905,14 @@ "r = client.post('/', data=dict(test_val='21', k='a', v='b'), headers={'HX-Request': '1'})\n", "test_eq(r.status_code, 200)\n", "print(r.text)" - ], - "id": "29d868c520d765ea" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "c0724d784ab594d1", + "metadata": {}, + "outputs": [], "source": [ "def g(req, this:Starlette, a:str, b:HttpHeader, state): ...\n", "\n", @@ -894,14 +923,14 @@ "client = TestClient(Starlette(routes=[Route('/', f, methods=['POST'])]))\n", "response = client.post('/?a=1', data=d)\n", "print(response.text)" - ], - "id": "c0724d784ab594d1" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "d0f92af0fbc7c0fd", + "metadata": {}, + "outputs": [], "source": [ "def g(req, this:Starlette, a:str, b:HttpHeader): ...\n", "\n", @@ -912,14 +941,14 @@ "client = TestClient(Starlette(routes=[Route('/', f, methods=['POST'])]))\n", "response = client.post('/?a=1', data=d)\n", "print(response.text)" - ], - "id": "d0f92af0fbc7c0fd" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "b396c52f3346caa7", + "metadata": {}, + "outputs": [], "source": [ "class Bar(BasicRepr):\n", " @classmethod\n", @@ -934,26 +963,30 @@ "\n", "client = TestClient(Starlette(routes=[Route('/', f, methods=['POST'])]))\n", "client.post('/', headers={'Accept': 'application/json'}).text" - ], - "id": "b396c52f3346caa7" + ] }, { - "metadata": {}, "cell_type": "markdown", - "source": "**Missing Request Params**", - "id": "78335a952aea05ad" + "id": "78335a952aea05ad", + "metadata": {}, + "source": [ + "**Missing Request Params**" + ] }, { - "metadata": {}, "cell_type": "markdown", - "source": "If a request param has a default value (e.g. `a:str=''`), the request is valid even if the user doesn't include the param in their request.", - "id": "a91254ccdac6ce7c" + "id": "a91254ccdac6ce7c", + "metadata": {}, + "source": [ + "If a request param has a default value (e.g. `a:str=''`), the request is valid even if the user doesn't include the param in their request." + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "b3db13a8d0036d32", + "metadata": {}, + "outputs": [], "source": [ "def g(req, this:Starlette, a:str=''): ...\n", "\n", @@ -964,20 +997,22 @@ "client = TestClient(Starlette(routes=[Route('/', f, methods=['POST'])]))\n", "response = client.post('/', json={}) # no param in request\n", "print(response.text)" - ], - "id": "b3db13a8d0036d32" + ] }, { - "metadata": {}, "cell_type": "markdown", - "source": "If we remove the default value and re-run the request, we should get the following error `Missing required field: a`.", - "id": "7f4162c89254077e" + "id": "7f4162c89254077e", + "metadata": {}, + "source": [ + "If we remove the default value and re-run the request, we should get the following error `Missing required field: a`." + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "fb7d7837e7ff6ba2", + "metadata": {}, + "outputs": [], "source": [ "def g(req, this:Starlette, a:str): ...\n", "\n", @@ -988,14 +1023,14 @@ "client = TestClient(Starlette(routes=[Route('/', f, methods=['POST'])]))\n", "response = client.post('/', json={}) # no param in request\n", "print(response.text)" - ], - "id": "fb7d7837e7ff6ba2" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "4b264f3ec9a80e3a", + "metadata": {}, + "outputs": [], "source": [ "#| export\n", "def flat_xt(lst):\n", @@ -1006,83 +1041,85 @@ " if isinstance(item, (list,tuple)): result.extend(item)\n", " else: result.append(item)\n", " return tuple(result)" - ], - "id": "4b264f3ec9a80e3a" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "d5ee5b99fc8fc445", + "metadata": {}, + "outputs": [], "source": [ "x = ft('a',1)\n", "test_eq(flat_xt([x, x, [x,x]]), (x,)*4)\n", "test_eq(flat_xt(x), (x,))" - ], - "id": "d5ee5b99fc8fc445" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "4b57d3d58af69e51", + "metadata": {}, + "outputs": [], "source": [ "#| export\n", "class Beforeware:\n", " \"Wrap a `before` function with `skip` path patterns that bypass it\"\n", " def __init__(self, f, skip=None): self.f,self.skip = f,skip or []\n", " def __repr__(self): return f'Beforeware({self.f}, skip={self.skip})'" - ], - "id": "4b57d3d58af69e51" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "de37dcd7b5641749", + "metadata": {}, + "outputs": [], "source": [ "#| export\n", "async def _handle(f, /, *args, **kwargs):\n", " return (await f(*args, **kwargs)) if is_async_callable(f) else await run_in_threadpool(f, *args, **kwargs)" - ], - "id": "de37dcd7b5641749" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "868b208fabcce9b6", + "metadata": {}, + "outputs": [], "source": [ "async def _f(f): return f\"got {f}\"\n", "test_eq(await _handle(_f, f='hello'), 'got hello')" - ], - "id": "868b208fabcce9b6" + ] }, { - "metadata": {}, "cell_type": "markdown", - "source": "## Websockets / SSE", - "id": "919baa8e3eb29d22" + "id": "919baa8e3eb29d22", + "metadata": {}, + "source": [ + "## Websockets / SSE" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "761597782f7f9df6", + "metadata": {}, + "outputs": [], "source": [ "#| export\n", "async def _wrap_ws(ws, data, params):\n", " raw = data.pop('HEADERS', {}) or (data.pop('headers') if isinstance(data.get('headers'), dict) else {}) # htmx v4 sends lowercase `headers`\n", " hdrs = Headers({k.lower():v for k,v in raw.items() if v is not None})\n", " return await _find_ps(ws, data, hdrs, params)" - ], - "id": "761597782f7f9df6" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "7a3be2b2f30770d7", + "metadata": {}, + "outputs": [], "source": [ "#| export\n", "async def _send_ws(ws, resp):\n", @@ -1111,14 +1148,14 @@ " if disconn: cls.on_disconnect = _disconnect\n", " cls.on_receive = _recv\n", " return cls" - ], - "id": "7a3be2b2f30770d7" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "a2237401400886a2", + "metadata": {}, + "outputs": [], "source": [ "def on_receive(msg:str): return f\"Message text was: {msg}\"\n", "c = _ws_endp(on_receive)\n", @@ -1127,14 +1164,14 @@ " ws.send_text('{\"msg\":\"Hi!\"}')\n", " data = ws.receive_text()\n", " assert data == 'Message text was: Hi!', data" - ], - "id": "a2237401400886a2" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "a73456aac0e74ecb", + "metadata": {}, + "outputs": [], "source": [ "def on_receive(hx_trigger:str): return f\"trigger: {hx_trigger}\"\n", "cli = TestClient(Starlette(routes=[WebSocketRoute('/', _ws_endp(on_receive))]))\n", @@ -1142,27 +1179,27 @@ " ws.send_text(json.dumps({\"HEADERS\": {\"Hx-Trigger\": \"my-btn\"}}))\n", " data = ws.receive_text()\n", " assert data == 'trigger: my-btn', data\n" - ], - "id": "a73456aac0e74ecb" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "ddc64ff604c831b8", + "metadata": {}, + "outputs": [], "source": [ "#| export\n", "def EventStream(s):\n", " \"Create a text/event-stream response from `s`\"\n", " return StreamingResponse(s, media_type=\"text/event-stream\")" - ], - "id": "ddc64ff604c831b8" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "2e11648d17d6d6f5", + "metadata": {}, + "outputs": [], "source": [ "#| export\n", "def signal_shutdown():\n", @@ -1175,58 +1212,60 @@ " self.force_exit = True\n", " self._orig_handle_exit(*args, **kwargs)\n", " return event" - ], - "id": "2e11648d17d6d6f5" + ] }, { - "metadata": {}, "cell_type": "markdown", - "source": "## Routing and application", - "id": "fc2f9df0b33fc305" + "id": "fc2f9df0b33fc305", + "metadata": {}, + "source": [ + "## Routing and application" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "f660c44ff209b90c", + "metadata": {}, + "outputs": [], "source": [ "#| export\n", "def uri(_arg, **kwargs):\n", " \"Create a URI by URL-encoding `_arg` and appending query parameters from `kwargs`\"\n", " return f\"{quote(_arg)}/{urlencode(kwargs, doseq=True)}\"" - ], - "id": "f660c44ff209b90c" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "3e45f287f5af27c5", + "metadata": {}, + "outputs": [], "source": [ "#| export\n", "def decode_uri(s):\n", " \"Decode a URI created by `uri()` back into argument and keyword dict\"\n", " arg,_,kw = s.partition('/')\n", " return unquote(arg), {k:v[0] for k,v in parse_qs(kw).items()}" - ], - "id": "3e45f287f5af27c5" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "580afa399f3bd333", + "metadata": {}, + "outputs": [], "source": [ "#| export\n", "from starlette.convertors import StringConvertor" - ], - "id": "580afa399f3bd333" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "2bb9a1ff5768ba68", + "metadata": {}, + "outputs": [], "source": [ "#| export\n", "StringConvertor.regex = \"[^/]*\" # `+` replaced with `*`\n", @@ -1237,28 +1276,28 @@ " assert \"/\" not in value, \"May not contain path separators\"\n", " # assert value, \"Must not be empty\" # line removed due to errors\n", " return value" - ], - "id": "2bb9a1ff5768ba68" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "d99b78e3a99c3ec0", + "metadata": {}, + "outputs": [], "source": [ "#| export\n", "@patch\n", "def url_path_for(self:HTTPConnection, name: str, **path_params):\n", " lp = self.scope['app'].url_path_for(name, **path_params)\n", " return URLPath(f\"{self.scope['root_path']}{lp}\", lp.protocol, lp.host)" - ], - "id": "d99b78e3a99c3ec0" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "c4d78aa8d576e6cc", + "metadata": {}, + "outputs": [], "source": [ "#| export\n", "_verbs = dict(get='hx-get', post='hx-post', put='hx-put', delete='hx-delete', patch='hx-patch', link='href')\n", @@ -1285,25 +1324,25 @@ " \"Convert response to XML string with target URL resolution\"\n", " _find_targets(req, resp)\n", " return to_xml(resp, indent=indent)" - ], - "id": "c4d78aa8d576e6cc" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "f2f473dc3aa8e232", + "metadata": {}, + "outputs": [], "source": [ "#| export\n", "_iter_typs = (tuple,list,map,filter,range,types.GeneratorType)" - ], - "id": "f2f473dc3aa8e232" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "ce31ff717114b811", + "metadata": {}, + "outputs": [], "source": [ "#| export\n", "def flat_tuple(o):\n", @@ -1315,27 +1354,27 @@ " if isinstance(item, _iter_typs): result.extend(list(item))\n", " else: result.append(item)\n", " return tuple(result)" - ], - "id": "ce31ff717114b811" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "aaf0c02fc0142c20", + "metadata": {}, + "outputs": [], "source": [ "#| export\n", "def noop_body(c, req):\n", " \"Default Body wrap function which just returns the content\"\n", " return c" - ], - "id": "aaf0c02fc0142c20" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "6df817363734849b", + "metadata": {}, + "outputs": [], "source": [ "#| export\n", "def respond(req, heads, bdy):\n", @@ -1345,37 +1384,37 @@ " bw_args = (bdy, req) if len(params)>1 else (bdy,)\n", " body = Body(body_wrap(*bw_args), *flat_xt(req.ftrs), **req.bodykw)\n", " return Html(Head(*heads, *flat_xt(req.hdrs)), body, **req.htmlkw)" - ], - "id": "6df817363734849b" + ] }, { - "metadata": {}, "cell_type": "markdown", + "id": "2a6054f74f4c9f90", + "metadata": {}, "source": [ "Render fragment if `HX-Request` header is _present_ and\n", " `HX-History-Restore-Request` header is _absent._" - ], - "id": "2a6054f74f4c9f90" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "2f96c17575a317a", + "metadata": {}, + "outputs": [], "source": [ "#| export\n", "def is_full_page(req, resp):\n", " \"Check if response should be rendered as full page or fragment\"\n", " if resp and any(getattr(o, 'tag', '')=='html' for o in resp): return True\n", " return 'hx-request' in req.headers and 'hx-history-restore-request' not in req.headers" - ], - "id": "2f96c17575a317a" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "99a2f618ca8e26e9", + "metadata": {}, + "outputs": [], "source": [ "#| export\n", "def _part_resp(req, resp):\n", @@ -1393,14 +1432,14 @@ " resp = tuple(resp)\n", " if len(resp)==1: resp = resp[0]\n", " return resp,kw" - ], - "id": "99a2f618ca8e26e9" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "d18dc765f6c377c3", + "metadata": {}, + "outputs": [], "source": [ "#| export\n", "def _canonical(req):\n", @@ -1417,27 +1456,27 @@ " title = [] if any(getattr(o, 'tag', '')=='title' for o in heads) else [Title(req.app.title)]\n", " resp = respond(req, [*heads, *title, *_canonical(req)], bdy)\n", " return _to_xml(req, resp, indent=fh_cfg.indent)" - ], - "id": "d18dc765f6c377c3" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "5afa1b8942912373", + "metadata": {}, + "outputs": [], "source": [ "#| export\n", "def _is_ft_resp(resp):\n", " \"Check if response is a FastTag-compatible type\"\n", " return isinstance(resp, _iter_typs+(HttpHeader,FT)) or hasattr(resp, '__ft__')" - ], - "id": "5afa1b8942912373" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "67c986c99e7a6231", + "metadata": {}, + "outputs": [], "source": [ "#| export\n", "def _resp(req, resp, cls=empty, status_code=200):\n", @@ -1458,14 +1497,14 @@ " resp = str(resp)\n", " cls = HTMLResponse\n", " return cls(resp, status_code=status_code, **kw)" - ], - "id": "67c986c99e7a6231" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "15e507d2acd3232e", + "metadata": {}, + "outputs": [], "source": [ "#| export\n", "class Redirect:\n", @@ -1474,28 +1513,28 @@ " def __response__(self, req):\n", " if 'hx-request' in req.headers: return HtmxResponseHeaders(redirect=self.loc)\n", " return RedirectResponse(self.loc, status_code=303)" - ], - "id": "15e507d2acd3232e" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "92a6fdb45add90f0", + "metadata": {}, + "outputs": [], "source": [ "#| export\n", "async def _wrap_call(f, req, params):\n", " \"Wrap function call with request parameter injection\"\n", " wreq = await _wrap_req(req, params)\n", " return await _handle(f, **wreq)" - ], - "id": "92a6fdb45add90f0" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "49c3d12b947fa377", + "metadata": {}, + "outputs": [], "source": [ "#| export\n", "# chkstyle: skip\n", @@ -1516,28 +1555,32 @@ " \"live\": \"https://cdn.jsdelivr.net/npm/htmx.org@4.0.0/dist/ext/hx-live.min.js\",\n", " \"multipart\": \"https://cdn.jsdelivr.net/npm/htmx.org@4.0.0/dist/ext/hx-multipart.min.js\"\n", "}" - ], - "id": "49c3d12b947fa377" + ] }, { - "metadata": {}, "cell_type": "markdown", - "source": "The FastHTML `exts` param supports the following:", - "id": "cf08377dacfc7dea" + "id": "cf08377dacfc7dea", + "metadata": {}, + "source": [ + "The FastHTML `exts` param supports the following:" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, - "source": "print(' '.join(htmx_exts))", - "id": "62a280661c939ed3" + "id": "62a280661c939ed3", + "metadata": {}, + "outputs": [], + "source": [ + "print(' '.join(htmx_exts))" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "b31e24130b390101", + "metadata": {}, + "outputs": [], "source": [ "#| export\n", "htmxsrc = Script(src=\"https://cdn.jsdelivr.net/npm/htmx.org@2.0.7/dist/htmx.js\")\n", @@ -1547,14 +1590,14 @@ "scopesrc = Script(src=\"https://cdn.jsdelivr.net/gh/gnat/css-scope-inline@main/script.js\")\n", "viewport = Meta(name=\"viewport\", content=\"width=device-width, initial-scale=1, viewport-fit=cover\")\n", "charset = Meta(charset=\"utf-8\")" - ], - "id": "b31e24130b390101" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "af5fa00cfaef7a8b", + "metadata": {}, + "outputs": [], "source": [ "#| export\n", "def get_key(key=None, fname='.sesskey'):\n", @@ -1565,27 +1608,27 @@ " key = str(uuid.uuid4())\n", " fname.write_text(key)\n", " return key" - ], - "id": "af5fa00cfaef7a8b" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "17ff3158cc805754", + "metadata": {}, + "outputs": [], "source": [ "#| export\n", "def _list(o):\n", " \"Wrap non-list item in a list, returning empty list if None\"\n", " return [] if not o else list(o) if isinstance(o, (tuple,list)) else [o]" - ], - "id": "17ff3158cc805754" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "d2a4061192d883e8", + "metadata": {}, + "outputs": [], "source": [ "#| export\n", "def _wrap_ex(f, status_code, hdrs, ftrs, htmlkw, bodykw, body_wrap):\n", @@ -1596,14 +1639,14 @@ " res = await _handle(f, req, exc)\n", " return _resp(req, res, status_code=status_code)\n", " return _f" - ], - "id": "d2a4061192d883e8" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "f0ddf2219c879e3b", + "metadata": {}, + "outputs": [], "source": [ "#| export\n", "def qp(p:str, **kw) -> str:\n", @@ -1616,57 +1659,63 @@ " p = re.sub(r'\\{([^:}]+)(:.+?)?}', _sub, p)\n", " # encode query params\n", " return p + ('?' + urlencode({k:'' if v in (False,None) else v for k,v in kw.items()},doseq=True) if kw else '')" - ], - "id": "f0ddf2219c879e3b" + ] }, { - "metadata": {}, "cell_type": "markdown", - "source": "`qp` adds query parameters to route path strings", - "id": "e117438a658aa761" + "id": "e117438a658aa761", + "metadata": {}, + "source": [ + "`qp` adds query parameters to route path strings" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, - "source": "vals = dict(a=5, b=False, c=[1,2], d='bar', e=None, ab=42)", - "id": "12f6b4803592427c" + "id": "12f6b4803592427c", + "metadata": {}, + "outputs": [], + "source": [ + "vals = dict(a=5, b=False, c=[1,2], d='bar', e=None, ab=42)" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "3e8752f87bea162b", + "metadata": {}, + "outputs": [], "source": [ "res = qp('/foo', **vals)\n", "test_eq(res, '/foo?a=5&b=&c=1&c=2&d=bar&e=&ab=42')" - ], - "id": "3e8752f87bea162b" + ] }, { - "metadata": {}, "cell_type": "markdown", - "source": "`qp` checks to see if each param should be sent as a query parameter or as part of the route, and encodes that properly.", - "id": "10f6e76c48f0572c" + "id": "10f6e76c48f0572c", + "metadata": {}, + "source": [ + "`qp` checks to see if each param should be sent as a query parameter or as part of the route, and encodes that properly." + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "19c390817bbfbdaf", + "metadata": {}, + "outputs": [], "source": [ "path = '/foo/{a}/{d}/{ab:int}'\n", "res = qp(path, **vals)\n", "test_eq(res, '/foo/5/bar/42?b=&c=1&c=2&e=')" - ], - "id": "19c390817bbfbdaf" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "8add43015a5b4c0c", + "metadata": {}, + "outputs": [], "source": [ "#| export\n", "def def_hdrs(htmx=True, htmx4=False, surreal=True):\n", @@ -1680,14 +1729,14 @@ " # TODO: Check if fhjsscr works with htmx4\n", " elif htmx: hdrs = [htmxsrc,fhjsscr] + hdrs\n", " return [charset, viewport] + hdrs" - ], - "id": "8add43015a5b4c0c" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "54f3bb368193da5c", + "metadata": {}, + "outputs": [], "source": [ "#| export\n", "cors_allow = Middleware(CORSMiddleware, allow_credentials=True, allow_origins=['*'], allow_methods=['*'], allow_headers=['*'])\n", @@ -1713,14 +1762,14 @@ " }\n", " };\n", "\"\"\"))\n" - ], - "id": "54f3bb368193da5c" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "876c9c8cb63f2cf2", + "metadata": {}, + "outputs": [], "source": [ "#| export\n", "class _LifespanCtx:\n", @@ -1748,14 +1797,14 @@ " for f in self.shutdown: await _handle(f)\n", "\n", " def on_event(self, event_type): return lambda f: (getattr(self, event_type)).append(f)" - ], - "id": "876c9c8cb63f2cf2" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "d8d78a64be4bf27", + "metadata": {}, + "outputs": [], "source": [ "#| export\n", "class FastHTML(Starlette):\n", @@ -1795,20 +1844,22 @@ " super().__init__(debug, routes, middleware=middleware, exception_handlers=excs, lifespan=self.lifespan)\n", "\n", " def on_event(self, event_type): return self.lifespan.on_event(event_type)" - ], - "id": "d8d78a64be4bf27" + ] }, { - "metadata": {}, "cell_type": "markdown", - "source": "### Routes", - "id": "76d26b7b94050a73" + "id": "76d26b7b94050a73", + "metadata": {}, + "source": [ + "### Routes" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "b000f60adf333122", + "metadata": {}, + "outputs": [], "source": [ "#| export\n", "class HostRoute(Route):\n", @@ -1827,14 +1878,14 @@ " def __repr__(self) -> str:\n", " methods = sorted(self.methods or [])\n", " return f\"{self.__class__.__name__}(path={self.path!r}, name={self.name!r}, methods={methods!r}, host={self.host!r})\"" - ], - "id": "b000f60adf333122" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "d673eda936d3ac03", + "metadata": {}, + "outputs": [], "source": [ "app = FastHTML()\n", "app.router.routes = []\n", @@ -1847,14 +1898,14 @@ "test_eq(cli.get('/', headers={'host': 'localhost'}).text, 'main page')\n", "test_eq(cli.get('/', headers={'host': 'auth.example.com'}).text, 'auth page')\n", "print('all passed')" - ], - "id": "d673eda936d3ac03" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "c2ba4ddbb35095f", + "metadata": {}, + "outputs": [], "source": [ "app.router.routes.append(HostRoute('/hello', lambda _: Response('api hello'), host='api.{parentdom}', methods=['GET'], name='api_hello'))\n", "app.router.routes.append(HostRoute('/hello', lambda _: Response('normal hello'), methods=['GET'], name='hello'))\n", @@ -1863,14 +1914,14 @@ "test_eq(cli.get('/hello', headers={'host': 'mysite.com'}).text, 'normal hello')\n", "test_eq(cli.get('/hello', headers={'host': 'other.mysite.com'}).text, 'normal hello')\n", "print('all passed')" - ], - "id": "c2ba4ddbb35095f" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "a1583c0bcb0420f2", + "metadata": {}, + "outputs": [], "source": [ "#| export\n", "@patch\n", @@ -1882,25 +1933,25 @@ " ((route.methods is None) or (set(r.methods) == set(route.methods))))]\n", " self.router.routes.append(route)\n", " self.router.routes.sort(key=lambda r: not getattr(r, 'host', None))\n" - ], - "id": "a1583c0bcb0420f2" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "4917c9f35ccd9f96", + "metadata": {}, + "outputs": [], "source": [ "#| export\n", "all_meths = 'get post put delete patch head trace options'.split()" - ], - "id": "4917c9f35ccd9f96" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "46ca67a58ad666b9", + "metadata": {}, + "outputs": [], "source": [ "#| export\n", "@patch\n", @@ -1930,14 +1981,14 @@ " if nr: resp = nr\n", " return _resp(req, resp, sig.return_annotation)\n", " return _f" - ], - "id": "46ca67a58ad666b9" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "a0744b04d81228d6", + "metadata": {}, + "outputs": [], "source": [ "#| export\n", "@patch\n", @@ -1948,14 +1999,14 @@ " route.methods = ['ws']\n", " self.add_route(route)\n", " return func" - ], - "id": "a0744b04d81228d6" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "2fc600349ae25291", + "metadata": {}, + "outputs": [], "source": [ "#| export\n", "@patch\n", @@ -1963,28 +2014,28 @@ " \"Add a websocket route at `path`\"\n", " def f(func=noop): return self._add_ws(func, path, conn, disconn, name=name, middleware=middleware)\n", " return f" - ], - "id": "2fc600349ae25291" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "17f6217b9e528764", + "metadata": {}, + "outputs": [], "source": [ "#|export\n", "@patch\n", "def add_websocket_route(self:FastHTML, path, func, conn=None, disconn=None, name=None, middleware=None):\n", " \"Add a websocket route at `path` (Starlette-compatible API)\"\n", " return self._add_ws(func, path, conn, disconn, name=name, middleware=middleware)" - ], - "id": "17f6217b9e528764" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "48e0a2670e869b6b", + "metadata": {}, + "outputs": [], "source": [ "#| export\n", "def _mk_locfunc(f, p, app=None):\n", @@ -1999,50 +2050,50 @@ " def __str__(self): return p\n", "\n", " return _lf()" - ], - "id": "48e0a2670e869b6b" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "a0c09d4bddc479a", + "metadata": {}, + "outputs": [], "source": [ "#| export\n", "def nested_name(f):\n", " \"Get name of function `f` using '_' to join nested function names\"\n", " return f.__qualname__.replace('..', '_')" - ], - "id": "a0c09d4bddc479a" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "1cadfcaba56484f5", + "metadata": {}, + "outputs": [], "source": [ "def f():\n", " def g(): ...\n", " return g" - ], - "id": "1cadfcaba56484f5" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "14dc3b2b623ea0f5", + "metadata": {}, + "outputs": [], "source": [ "func = f()\n", "nested_name(func)" - ], - "id": "14dc3b2b623ea0f5" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "8f0115f7adff7835", + "metadata": {}, + "outputs": [], "source": [ "#| export\n", "@patch\n", @@ -2055,14 +2106,14 @@ " handler = getattr(cls, meth, None)\n", " if handler: self._add_route(handler, path, meth, name, include_in_schema, body_wrap, host=host, before=before)\n", " return lf" - ], - "id": "8f0115f7adff7835" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "329e78f5bbc6ded1", + "metadata": {}, + "outputs": [], "source": [ "#| export\n", "def _route_pn(func, path, name):\n", @@ -2088,14 +2139,14 @@ " lf = _mk_locfunc(func, p, app=self)\n", " lf.__routename__ = n\n", " return lf" - ], - "id": "329e78f5bbc6ded1" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "ebf0ff44a915aa0c", + "metadata": {}, + "outputs": [], "source": [ "#| export\n", "@patch\n", @@ -2106,47 +2157,49 @@ " return f(path) if callable(path) else f\n", "\n", "for o in all_meths: setattr(FastHTML, o, partialmethod(FastHTML.route, methods=o))" - ], - "id": "ebf0ff44a915aa0c" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, - "source": [ + "id": "d7e65f487811260a", + "metadata": {}, + "outputs": [], + "source": [ "app = FastHTML()\n", "@app.get\n", "def foo(a:str, b:list[int]): ...\n", "\n", "foo.to(a='bar', b=[1,2])" - ], - "id": "d7e65f487811260a" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "256527283aa9a22c", + "metadata": {}, + "outputs": [], "source": [ "@app.get('/foo/{a}')\n", "def foo(a:str, b:list[int]): ...\n", "\n", "foo.to(a='bar', b=[1,2])" - ], - "id": "256527283aa9a22c" + ] }, { - "metadata": {}, "cell_type": "markdown", - "source": "### Utils", - "id": "8e67c9cd986ebcad" + "id": "8e67c9cd986ebcad", + "metadata": {}, + "source": [ + "### Utils" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "94d6f8f81d93aa5e", + "metadata": {}, + "outputs": [], "source": [ "#| export\n", "@patch\n", @@ -2154,14 +2207,14 @@ " \"Set the lifespan context manager for the FastHTML app\"\n", " if inspect.isasyncgenfunction(value): value = contextlib.asynccontextmanager(value)\n", " self.router.lifespan_context = value" - ], - "id": "94d6f8f81d93aa5e" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "b5e55224f5a20d18", + "metadata": {}, + "outputs": [], "source": [ "#| export\n", "def serve(\n", @@ -2188,20 +2241,22 @@ " link = f'http://{\"localhost\" if host==\"0.0.0.0\" else host}:{port}'\n", " print('Link: '+ S.light_red.bold(link))\n", " run(f'{appname}:{app}', host=host, port=port, reload=reload, **kwargs)" - ], - "id": "b5e55224f5a20d18" + ] }, { - "metadata": {}, "cell_type": "markdown", - "source": "`procs` runs the app as that many processes on consecutive ports from `port`, each with its own reload supervisor, and defaults to the `PROCS` environment variable. `serve` re-executes the script once per process with `FH_PROCNUM` set to its number, which is also the guard against a child spawning again. An app reads `FH_PROCNUM` for work that only one process should do, such as a background job: it is `'0'` in the first process, and unset in an ordinary single-process run. A reverse proxy in front of the ports decides how requests reach them.", - "id": "a5732f9665767807" + "id": "a5732f9665767807", + "metadata": {}, + "source": [ + "`procs` runs the app as that many processes on consecutive ports from `port`, each with its own reload supervisor, and defaults to the `PROCS` environment variable. `serve` re-executes the script once per process with `FH_PROCNUM` set to its number, which is also the guard against a child spawning again. An app reads `FH_PROCNUM` for work that only one process should do, such as a background job: it is `'0'` in the first process, and unset in an ordinary single-process run. A reverse proxy in front of the ports decides how requests reach them." + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "ddc667c24b6df7dc", + "metadata": {}, + "outputs": [], "source": [ "#| export\n", "def _spawn(n):\n", @@ -2209,20 +2264,22 @@ " ps = [subprocess.Popen([sys.executable, *sys.argv], env={**os.environ, 'FH_PROCNUM':str(i)}) for i in range(n)]\n", " signal.signal(signal.SIGTERM, lambda *a: [p.terminate() for p in ps])\n", " for p in ps: p.wait()" - ], - "id": "ddc667c24b6df7dc" + ] }, { - "metadata": {}, "cell_type": "markdown", - "source": "Starlette does not cancel a running handler when a client disconnects: the disconnect is only visible as an `http.disconnect` message on the ASGI receive channel, which ordinary handlers never read. `until_disconnect` races a coroutine against that message, cancelling the work if the client goes away first.", - "id": "6562a9b295a6e9f8" + "id": "6562a9b295a6e9f8", + "metadata": {}, + "source": [ + "Starlette does not cancel a running handler when a client disconnects: the disconnect is only visible as an `http.disconnect` message on the ASGI receive channel, which ordinary handlers never read. `until_disconnect` races a coroutine against that message, cancelling the work if the client goes away first." + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "78dc3bffc42b5d1", + "metadata": {}, + "outputs": [], "source": [ "#| export\n", "async def _wait_disconnect(req):\n", @@ -2238,20 +2295,22 @@ " finally:\n", " watch.cancel()\n", " if not work.done(): work.cancel()" - ], - "id": "78dc3bffc42b5d1" + ] }, { - "metadata": {}, "cell_type": "markdown", - "source": "`cancel_on_disconnect` applies this to a route handler. `splice_sig` adds a private `Request`-annotated parameter to the exposed signature, which FastHTML fills with the connection, so the handler's own parameters are unchanged. It requires an async handler, since a sync handler runs in a threadpool and cannot be cancelled.", - "id": "a4d7ea6dd8b142af" + "id": "a4d7ea6dd8b142af", + "metadata": {}, + "source": [ + "`cancel_on_disconnect` applies this to a route handler. `splice_sig` adds a private `Request`-annotated parameter to the exposed signature, which FastHTML fills with the connection, so the handler's own parameters are unchanged. It requires an async handler, since a sync handler runs in a threadpool and cannot be cancelled." + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "3ddda418760bb472", + "metadata": {}, + "outputs": [], "source": [ "#| export\n", "def cancel_on_disconnect(\n", @@ -2266,14 +2325,14 @@ " c = until_disconnect(__req, f(**kw))\n", " return await (asyncio.wait_for(c, timeout) if timeout is not None else c)\n", " return splice_sig(_f, f)" - ], - "id": "3ddda418760bb472" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "33e9385190411631", + "metadata": {}, + "outputs": [], "source": [ "#| export\n", "class Client:\n", @@ -2287,55 +2346,63 @@ " with from_thread.start_blocking_portal() as portal: return portal.call(_request)\n", "\n", "for o in ('get', 'post', 'delete', 'put', 'patch', 'options'): setattr(Client, o, partialmethod(Client._sync, o))" - ], - "id": "33e9385190411631" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "201775479e8c5e4d", + "metadata": {}, + "outputs": [], "source": [ "app = FastHTML(routes=[Route('/', lambda _: Response('test'))])\n", "cli = Client(app)\n", "\n", "cli.get('/').text" - ], - "id": "201775479e8c5e4d" + ] }, { - "metadata": {}, "cell_type": "markdown", - "source": "Note that you can also use Starlette's `TestClient` instead of FastHTML's `Client`. They should be largely interchangable.", - "id": "a935603ded43699" + "id": "a935603ded43699", + "metadata": {}, + "source": [ + "Note that you can also use Starlette's `TestClient` instead of FastHTML's `Client`. They should be largely interchangable." + ] }, { - "metadata": {}, "cell_type": "markdown", - "source": "## FastHTML Tests", - "id": "6b039d58b7ad938c" + "id": "6b039d58b7ad938c", + "metadata": {}, + "source": [ + "## FastHTML Tests" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, - "source": "def get_cli(app): return app,TestClient(app),app.route", - "id": "7447e238bc623b35" + "id": "7447e238bc623b35", + "metadata": {}, + "outputs": [], + "source": [ + "def get_cli(app): return app,TestClient(app),app.route" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, - "source": "app,cli,rt = get_cli(FastHTML(secret_key='soopersecret'))", - "id": "1bf62de2b22c7f0c" + "id": "1bf62de2b22c7f0c", + "metadata": {}, + "outputs": [], + "source": [ + "app,cli,rt = get_cli(FastHTML(secret_key='soopersecret'))" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "d90ee04d8045202b", + "metadata": {}, + "outputs": [], "source": [ "app,cli,rt = get_cli(FastHTML(title=\"My Custom Title\"))\n", "@app.get\n", @@ -2347,14 +2414,14 @@ "assert 'My Custom Title' in response.text\n", "\n", "foo.to(param='value')" - ], - "id": "d90ee04d8045202b" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "47ef7be9d158140f", + "metadata": {}, + "outputs": [], "source": [ "@rt(host='test.foo')\n", "def foo(): return Div(\"Goodbye World\")\n", @@ -2363,27 +2430,27 @@ "\n", "assert \"Goodbye World\" in cli.get('/foo', headers={'host': 'test.foo'}).text\n", "assert \"Hello World\" in cli.get('/foo').text" - ], - "id": "47ef7be9d158140f" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "b943b2cdaf919cb4", + "metadata": {}, + "outputs": [], "source": [ "response = cli.get('/foo')\n", "assert 'My Custom Title' in response.text\n", "\n", "foo.to(param='value')" - ], - "id": "b943b2cdaf919cb4" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "92ccb75904de8458", + "metadata": {}, + "outputs": [], "source": [ "app,cli,rt = get_cli(FastHTML())\n", "\n", @@ -2392,26 +2459,26 @@ "\n", "txt = cli.get('/xt2').text\n", "assert 'FastHTML page' in txt and '

bar

' in txt and '' in txt" - ], - "id": "92ccb75904de8458" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "20cc2bf645b7006d", + "metadata": {}, + "outputs": [], "source": [ "def test_r(cli, path, exp, meth='get', hx=False, **kwargs):\n", " if hx: kwargs['headers'] = {'hx-request':\"1\"}\n", " test_eq(getattr(cli, meth)(path, **kwargs).text, exp)" - ], - "id": "20cc2bf645b7006d" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "944a5a468d63cacd", + "metadata": {}, + "outputs": [], "source": [ "@dataclass\n", "class Card: id:str; title:str\n", @@ -2426,14 +2493,14 @@ "test_r(cli, '/class-cards/abc', '{\"id\":\"abc\",\"title\":\"Foo\"}', 'patch', data={'title':'Foo'})\n", "test_eq(cli.delete('/class-cards/abc').text, 'delete abc')\n", "test_eq(CardMethods.to(id='xyz'), '/class-cards/xyz')" - ], - "id": "944a5a468d63cacd" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "b1237fb2b56936f7", + "metadata": {}, + "outputs": [], "source": [ "@rt\n", "class Things:\n", @@ -2441,54 +2508,54 @@ "\n", "test_eq(cli.get('/things?id=7').text, 'thing 7')\n", "test_eq(Things.to(id=7), '/things?id=7')" - ], - "id": "b1237fb2b56936f7" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "8c9af7970bef9521", + "metadata": {}, + "outputs": [], "source": [ "@rt(\"/hi\")\n", "def get(): return 'Hi there'\n", "\n", "r = cli.get('/hi')\n", "r.text" - ], - "id": "8c9af7970bef9521" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "c61831785468d85", + "metadata": {}, + "outputs": [], "source": [ "@rt(\"/hi\")\n", "def post(): return 'Postal'\n", "\n", "cli.post('/hi').text" - ], - "id": "c61831785468d85" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "5b9b648519a9841", + "metadata": {}, + "outputs": [], "source": [ "@app.get(\"/hostie\")\n", "def show_host(req): return req.headers['host']\n", "\n", "cli.get('/hostie').text" - ], - "id": "5b9b648519a9841" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "c8c78e969d888a8", + "metadata": {}, + "outputs": [], "source": [ "@app.get(\"/setsess\")\n", "def set_sess(session):\n", @@ -2504,100 +2571,100 @@ " data = ws.receive_text()\n", "assert 'Message text was: Hi! with session bar' in data\n", "print(data)" - ], - "id": "c8c78e969d888a8" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "5ae370e0b73ee395", + "metadata": {}, + "outputs": [], "source": [ "@rt\n", "def yoyo(): return 'a yoyo'\n", "\n", "cli.post('/yoyo').text" - ], - "id": "5ae370e0b73ee395" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "6910ecf551279150", + "metadata": {}, + "outputs": [], "source": [ "@app.get\n", "def autopost(): return Html(Div('Text.', hx_post=yoyo()))\n", "print(cli.get('/autopost').text)" - ], - "id": "6910ecf551279150" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "a7ee02f019c404e9", + "metadata": {}, + "outputs": [], "source": [ "@app.get\n", "def autopost2(): return Html(Body(Div('Text.', cls='px-2', hx_post=show_host.to(a='b'))))\n", "print(cli.get('/autopost2').text)" - ], - "id": "a7ee02f019c404e9" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "3fd2e6ee0954afe7", + "metadata": {}, + "outputs": [], "source": [ "@app.get\n", "def autoget2(): return Html(Div('Text.', hx_get=show_host))\n", "print(cli.get('/autoget2').text)" - ], - "id": "3fd2e6ee0954afe7" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "97af5cc25eac0664", + "metadata": {}, + "outputs": [], "source": [ "@rt('/user/{nm}', name='gday')\n", "def get(nm:str=''): return f\"Good day to you, {nm}!\"\n", "cli.get('/user/Alexis').text" - ], - "id": "97af5cc25eac0664" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "79fe68f310ade29e", + "metadata": {}, + "outputs": [], "source": [ "@app.get\n", "def autolink(): return Html(Div('Text.', link=uri('gday', nm='Alexis')))\n", "print(cli.get('/autolink').text)" - ], - "id": "79fe68f310ade29e" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "4c9d807ad8da2122", + "metadata": {}, + "outputs": [], "source": [ "@rt('/link')\n", "def get(req): return f\"{req.url_for('gday', nm='Alexis')}; {req.url_for('show_host')}\"\n", "\n", "cli.get('/link').text" - ], - "id": "4c9d807ad8da2122" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "7c0d763cf3ba98d4", + "metadata": {}, + "outputs": [], "source": [ "@app.get(\"/background\")\n", "async def background_task(request):\n", @@ -2607,22 +2674,24 @@ " return P(\"Task started\"), BackgroundTask(long_running_task)\n", "\n", "response = cli.get(\"/background\")" - ], - "id": "7c0d763cf3ba98d4" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, - "source": "test_eq(app.router.url_path_for('gday', nm='Jeremy'), '/user/Jeremy')", - "id": "d30c01e9258d35de" + "id": "d30c01e9258d35de", + "metadata": {}, + "outputs": [], + "source": [ + "test_eq(app.router.url_path_for('gday', nm='Jeremy'), '/user/Jeremy')" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "398b0258281fbb65", + "metadata": {}, + "outputs": [], "source": [ "hxhdr = {'headers':{'hx-request':\"1\"}}\n", "\n", @@ -2645,62 +2714,62 @@ "\n", "txt = cli.get('/xt3').text\n", "assert 'FastHTML page' not in txt and 'hi' in txt and '

there

' in txt" - ], - "id": "398b0258281fbb65" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "eeccde59428d6528", + "metadata": {}, + "outputs": [], "source": [ "# declaration-time warnings\n", "def _noanno(nope): return nope\n", "def _bare(names:list): return str(names)\n", "test_warns(lambda: rt('/oops')(_noanno))\n", "test_warns(lambda: rt('/barelist')(_bare))" - ], - "id": "eeccde59428d6528" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "57158b1cf3f65ee", + "metadata": {}, + "outputs": [], "source": [ "# runtime warnings\n", "test_warns(lambda: cli.get('/oops?nope=1'))\n", "test_warns(lambda: cli.get('/barelist?names=1'))" - ], - "id": "57158b1cf3f65ee" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "7677f45b7e3fd7f9", + "metadata": {}, + "outputs": [], "source": [ "ModelName = str_enum('ModelName', \"alexnet\", \"resnet\", \"lenet\")\n", "fake_db = [{\"name\": \"Foo\"}, {\"name\": \"Bar\"}]" - ], - "id": "7677f45b7e3fd7f9" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "accee413b1b66b81", + "metadata": {}, + "outputs": [], "source": [ "@rt('/html/{idx}')\n", "async def get(idx:int): return Body(H4(f'Next is {idx+1}.'))" - ], - "id": "accee413b1b66b81" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "f8f507e3ab671ab", + "metadata": {}, + "outputs": [], "source": [ "@rt(\"/models/{nm}\")\n", "def get(nm:ModelName): return nm\n", @@ -2719,14 +2788,14 @@ "\n", "@rt(\"/unionidxl/\")\n", "def get(idx:list[int] | None): return str(idx)" - ], - "id": "f8f507e3ab671ab" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "4fb9b3ffc59ce351", + "metadata": {}, + "outputs": [], "source": [ "r = cli.get('/html/1', headers={'hx-request':\"1\"})\n", "assert '

Next is 2.

' in r.text\n", @@ -2740,14 +2809,14 @@ "assert cli.get('/idxl/?idx=1&idx=g').status_code == 404\n", "test_r(cli, '/optidxl/?idx=1&idx=2', '[1, 2]')\n", "test_r(cli, '/unionidxl/?idx=1&idx=2', '[1, 2]')" - ], - "id": "4fb9b3ffc59ce351" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "2e1dda2d25a8e885", + "metadata": {}, + "outputs": [], "source": [ "app = FastHTML()\n", "rt = app.route\n", @@ -2757,30 +2826,34 @@ "@app.route(r'/static/{path:path}')\n", "def foo(path:str, a:int): return f'also got {path},{a}'\n", "cli.get('/static/sub/a.b.jpg').text" - ], - "id": "2e1dda2d25a8e885" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, - "source": "cli.get('/static/sub/a.b?a=1').text", - "id": "7e193da57daea07b" + "id": "7e193da57daea07b", + "metadata": {}, + "outputs": [], + "source": [ + "cli.get('/static/sub/a.b?a=1').text" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, - "source": "app.chk = 'foo'", - "id": "f87c9a5d4ea90f29" + "id": "f87c9a5d4ea90f29", + "metadata": {}, + "outputs": [], + "source": [ + "app.chk = 'foo'" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "503d7efff37dbc47", + "metadata": {}, + "outputs": [], "source": [ "@app.get(\"/booly/\")\n", "def _(coming:bool=True): return 'Coming' if coming else 'Not coming'\n", @@ -2808,14 +2881,14 @@ "\n", "@app.get(\"/app4\")\n", "def _(foo:FastHTML): return Redirect(\"http://example.org\")" - ], - "id": "503d7efff37dbc47" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "263790ff5a34a051", + "metadata": {}, + "outputs": [], "source": [ "test_r(cli, '/booly/?coming=true', 'Coming')\n", "test_r(cli, '/booly/?coming=no', 'Not coming')\n", @@ -2825,59 +2898,59 @@ "test_r(cli, '/hxtest' , '1', headers={'HX-Request':'1'})\n", "test_r(cli, '/hxtest2', '1', headers={'HX-Request':'1'})\n", "test_r(cli, '/app' , 'foo')" - ], - "id": "263790ff5a34a051" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "b776724e467f3653", + "metadata": {}, + "outputs": [], "source": [ "r = cli.get('/app2', **hxhdr)\n", "test_eq(r.text, 'foo')\n", "test_eq(r.headers['mykey'], 'myval')" - ], - "id": "b776724e467f3653" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "9370a01559dacd73", + "metadata": {}, + "outputs": [], "source": [ "r = cli.get('/app3')\n", "test_eq(r.headers['HX-Location'], 'http://example.org')" - ], - "id": "9370a01559dacd73" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "236a2baa2c8b9c1a", + "metadata": {}, + "outputs": [], "source": [ "r = cli.get('/app4', follow_redirects=False)\n", "test_eq(r.status_code, 303)" - ], - "id": "236a2baa2c8b9c1a" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "963cb71a663fcd10", + "metadata": {}, + "outputs": [], "source": [ "r = cli.get('/app4', headers={'HX-Request':'1'})\n", "test_eq(r.headers['HX-Redirect'], 'http://example.org')" - ], - "id": "963cb71a663fcd10" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "e5b1bb2a658ea4e2", + "metadata": {}, + "outputs": [], "source": [ "@rt\n", "def meta(): return ((Title('hi'), H1('hi')), (Meta(property='image'), Meta(property='site_name')))\n", @@ -2885,28 +2958,28 @@ "t = cli.post('/meta').text\n", "assert re.search(r'\\s*

hi

\\s*', t)\n", "assert 'It worked!\" in response and \"

15, Lorem

\" in response" - ], - "id": "c796ffa8bb41da4" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "9179df36c8b757c6", + "metadata": {}, + "outputs": [], "source": [ "# Testing POST with Content-Type: application/json\n", "@app.post(\"/bodytext\")\n", @@ -3011,22 +3086,24 @@ "\n", "response = cli.post('/bodytext', headers={\"Content-Type\": \"application/json\"}, data=s).text\n", "test_eq(response, '{\"b\": \"Lorem\", \"a\": 15}')" - ], - "id": "9179df36c8b757c6" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, - "source": "files = [('files', ('file1.txt', b'content1')), ('files', ('file2.txt', b'content2'))]", - "id": "fd78230d02188eba" + "id": "fd78230d02188eba", + "metadata": {}, + "outputs": [], + "source": [ + "files = [('files', ('file1.txt', b'content1')), ('files', ('file2.txt', b'content2'))]" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "2faaeeb96a798748", + "metadata": {}, + "outputs": [], "source": [ "@rt(\"/uploads\")\n", "async def post(files:list[UploadFile]): return ','.join([(await file.read()).decode() for file in files])\n", @@ -3034,26 +3111,26 @@ "res = cli.post('/uploads', files=files)\n", "print(res.status_code)\n", "print(res.text)" - ], - "id": "2faaeeb96a798748" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "820cbae8934798f5", + "metadata": {}, + "outputs": [], "source": [ "res = cli.post('/uploads', files=[files[0]])\n", "test_eq(res.status_code, 200)\n", "test_eq(res.text, 'content1')" - ], - "id": "820cbae8934798f5" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "e988e94bfe6fba68", + "metadata": {}, + "outputs": [], "source": [ "@rt(\"/setsess\")\n", "def get(sess, foo:str=''):\n", @@ -3068,14 +3145,14 @@ "time.sleep(0.01)\n", "\n", "cli.get('/getsess').text" - ], - "id": "e988e94bfe6fba68" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "bf2d409c0709af67", + "metadata": {}, + "outputs": [], "source": [ "@rt(\"/sess-first\")\n", "def post(sess, name: str):\n", @@ -3088,59 +3165,61 @@ "def get(sess): return sess['name']\n", "\n", "test_eq(cli.get('/getsess-all').text, '2')" - ], - "id": "bf2d409c0709af67" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "df8d61ec976265b6", + "metadata": {}, + "outputs": [], "source": [ "@rt(\"/upload\")\n", "async def post(uf:UploadFile): return (await uf.read()).decode()\n", "\n", "with open('../../CHANGELOG.md', 'rb') as f: print(cli.post('/upload', files={'uf':f}, data={'msg':'Hello'}).text[:15])" - ], - "id": "df8d61ec976265b6" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "cbec41e8d6ebffbf", + "metadata": {}, + "outputs": [], "source": [ "@rt(\"/form-submit/{list_id}\")\n", "def options(list_id: str):\n", " headers = {'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'POST', 'Access-Control-Allow-Headers': '*'}\n", " return Response(status_code=200, headers=headers)" - ], - "id": "cbec41e8d6ebffbf" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "f1eb7890173765c6", + "metadata": {}, + "outputs": [], "source": [ "h = cli.options('/form-submit/2').headers\n", "test_eq(h['Access-Control-Allow-Methods'], 'POST')" - ], - "id": "f1eb7890173765c6" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, - "source": "from fasthtml.authmw import user_pwd_auth", - "id": "7482ef2bc589b29a" + "id": "7482ef2bc589b29a", + "metadata": {}, + "outputs": [], + "source": [ + "from fasthtml.authmw import user_pwd_auth" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "6f6ce6fd47d4b248", + "metadata": {}, + "outputs": [], "source": [ "def _not_found(req, exc): return Div('nope')\n", "\n", @@ -3149,14 +3228,14 @@ "txt = cli.get('/').text\n", "assert '
nope
' in txt\n", "assert '' in txt" - ], - "id": "6f6ce6fd47d4b248" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "5304bb2450fc035a", + "metadata": {}, + "outputs": [], "source": [ "app,cli,rt = get_cli(FastHTML())\n", "\n", @@ -3165,14 +3244,14 @@ "\n", "assert 'Hello Uma, age 5' in cli.get('/uma/5').text\n", "assert '404 Not Found' in cli.get('/uma/five').text" - ], - "id": "5304bb2450fc035a" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "38bb1202868cd0df", + "metadata": {}, + "outputs": [], "source": [ "auth = user_pwd_auth(testuser='spycraft')\n", "app,cli,rt = get_cli(FastHTML(middleware=[auth]))\n", @@ -3182,14 +3261,14 @@ "\n", "test_eq(cli.get('/locked').text, 'not authenticated')\n", "test_eq(cli.get('/locked', auth=(\"testuser\",\"spycraft\")).text, 'Hello, testuser')" - ], - "id": "38bb1202868cd0df" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "2e8d23e994bcbe96", + "metadata": {}, + "outputs": [], "source": [ "auth = user_pwd_auth(testuser='spycraft')\n", "app,cli,rt = get_cli(FastHTML(middleware=[auth]))\n", @@ -3199,28 +3278,32 @@ "\n", "test_eq(cli.get('/locked').text, 'not authenticated')\n", "test_eq(cli.get('/locked', auth=(\"testuser\",\"spycraft\")).text, 'Hello, testuser')" - ], - "id": "2e8d23e994bcbe96" + ] }, { - "metadata": {}, "cell_type": "markdown", - "source": "Check that afterware like toasts are called correctly.", - "id": "4bd6dcf2a8549622" + "id": "4bd6dcf2a8549622", + "metadata": {}, + "source": [ + "Check that afterware like toasts are called correctly." + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, - "source": "from fasthtml.toaster import *", - "id": "6cffaaba44df4e12" + "id": "6cffaaba44df4e12", + "metadata": {}, + "outputs": [], + "source": [ + "from fasthtml.toaster import *" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "36d8890a984cde1b", + "metadata": {}, + "outputs": [], "source": [ "app,cli,rt = get_cli(FastHTML())\n", "\n", @@ -3255,28 +3338,32 @@ "\n", "r = cli.get('/')\n", "assert tm in r.text" - ], - "id": "36d8890a984cde1b" + ] }, { - "metadata": {}, "cell_type": "markdown", - "source": "Here's a quick sanity check to confirm that toasts are rendered in the toast container correctly. See [issue](https://github.com/AnswerDotAI/fasthtml/issues/762).", - "id": "853dfc9923eb07d8" + "id": "853dfc9923eb07d8", + "metadata": {}, + "source": [ + "Here's a quick sanity check to confirm that toasts are rendered in the toast container correctly. See [issue](https://github.com/AnswerDotAI/fasthtml/issues/762)." + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, - "source": "assert 'id=\"fh-toast-container\"' in r.text", - "id": "14e38fb55813792c" + "id": "14e38fb55813792c", + "metadata": {}, + "outputs": [], + "source": [ + "assert 'id=\"fh-toast-container\"' in r.text" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "d5bb7f15f5fcaa7a", + "metadata": {}, + "outputs": [], "source": [ "app,cli,rt = get_cli(FastHTML(on_startup=[lambda: setattr(app, '_started', True)],\n", " on_shutdown=[lambda: setattr(app, '_stopped', True)]))\n", @@ -3286,14 +3373,14 @@ "\n", "with cli: test_eq(cli.get('/').text, 'True')\n", "test_eq(app._stopped, True)" - ], - "id": "d5bb7f15f5fcaa7a" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "8902976232842503", + "metadata": {}, + "outputs": [], "source": [ "app,cli,rt = get_cli(FastHTML())\n", "\n", @@ -3304,20 +3391,22 @@ "def index(): return app._evt\n", "\n", "with cli: test_eq(cli.get('/').text, 'fired')" - ], - "id": "8902976232842503" + ] }, { - "metadata": {}, "cell_type": "markdown", - "source": "A route-level `before` can set session data, short-circuit with a response, or raise to block access:", - "id": "a0d45421f11c25b9" + "id": "a0d45421f11c25b9", + "metadata": {}, + "source": [ + "A route-level `before` can set session data, short-circuit with a response, or raise to block access:" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "7cca7cdab970d0d5", + "metadata": {}, + "outputs": [], "source": [ "def check_user(sess, user:str=''):\n", " if user == 'admin':\n", @@ -3332,20 +3421,22 @@ "test_eq(cli.get('/dashboard?user=admin').text, 'bar')\n", "test_eq(cli.get('/dashboard?user=guest').text, 'guest view')\n", "test_eq(cli.get('/dashboard?user=other').status_code, 403)" - ], - "id": "7cca7cdab970d0d5" + ] }, { - "metadata": {}, "cell_type": "markdown", - "source": "Multiple `before` functions run in order, each receiving the injected request params:", - "id": "bbb9a2213e17475e" + "id": "bbb9a2213e17475e", + "metadata": {}, + "source": [ + "Multiple `before` functions run in order, each receiving the injected request params:" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "4bde7a5b2cce99a8", + "metadata": {}, + "outputs": [], "source": [ "def set_a(sess): sess['a'] = 1\n", "def set_b(sess): sess['b'] = 2\n", @@ -3354,20 +3445,22 @@ "def get(sess): return f\"{sess.get('a')},{sess.get('b')}\"\n", "\n", "test_eq(cli.get('/multi').text, '1,2')" - ], - "id": "4bde7a5b2cce99a8" + ] }, { - "metadata": {}, "cell_type": "markdown", - "source": "A truthy return from any `before` becomes the response; remaining `before`s and the handler are skipped (return `None` to continue):", - "id": "744158410961fec" + "id": "744158410961fec", + "metadata": {}, + "source": [ + "A truthy return from any `before` becomes the response; remaining `before`s and the handler are skipped (return `None` to continue):" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "e8ef438896db58e", + "metadata": {}, + "outputs": [], "source": [ "calls = []\n", "def first(sess): \n", @@ -3380,20 +3473,22 @@ "\n", "test_eq(cli.get('/chain').text, 'stop')\n", "test_eq(calls, ['first'])" - ], - "id": "e8ef438896db58e" + ] }, { - "metadata": {}, "cell_type": "markdown", - "source": "`cancel_on_disconnect` handlers keep their normal parameters; the handler is cancelled if the client disconnects, or after `timeout` seconds if given:", - "id": "88f8a5f93a0ef7a" + "id": "88f8a5f93a0ef7a", + "metadata": {}, + "source": [ + "`cancel_on_disconnect` handlers keep their normal parameters; the handler is cancelled if the client disconnects, or after `timeout` seconds if given:" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "85ed9def2ea9228", + "metadata": {}, + "outputs": [], "source": [ "app,cli,rt = get_cli(FastHTML())\n", "\n", @@ -3402,14 +3497,14 @@ "async def cq(q:str): return f'got {q}'\n", "\n", "test_eq(cli.get('/cq?q=x').text, 'got x')" - ], - "id": "85ed9def2ea9228" + ] }, { - "metadata": {}, "cell_type": "code", + "execution_count": null, + "id": "fea470bc5d427298", + "metadata": {}, "outputs": [], - "execution_count": null, "source": [ "@rt('/sleepy')\n", "@cancel_on_disconnect(timeout=0.01)\n", @@ -3418,20 +3513,22 @@ " return 'nope'\n", "\n", "test_fail(lambda: cli.get('/sleepy'))" - ], - "id": "fea470bc5d427298" + ] }, { - "metadata": {}, "cell_type": "markdown", - "source": "On disconnect the handler is cancelled and an empty response returned, which the server discards since the client is gone. Here we simulate the ASGI `http.disconnect` message directly:", - "id": "cedb36782bbf9ac" + "id": "cedb36782bbf9ac", + "metadata": {}, + "source": [ + "On disconnect the handler is cancelled and an empty response returned, which the server discards since the client is gone. Here we simulate the ASGI `http.disconnect` message directly:" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "a593ee4bedcabe79", + "metadata": {}, + "outputs": [], "source": [ "async def _disc(): return {'type': 'http.disconnect'}\n", "cancelled = []\n", @@ -3449,20 +3546,22 @@ "\n", "test_eq(run_sync(_t()).status_code, 204)\n", "test_eq(cancelled, [True])" - ], - "id": "a593ee4bedcabe79" + ] }, { - "metadata": {}, "cell_type": "markdown", - "source": "## APIRouter", - "id": "4b7fc45fa7b0fb5c" + "id": "4b7fc45fa7b0fb5c", + "metadata": {}, + "source": [ + "## APIRouter" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "d00984c329331d4", + "metadata": {}, + "outputs": [], "source": [ "#| export\n", "class RouteFuncs:\n", @@ -3474,14 +3573,14 @@ " try: return self._funcs[name]\n", " except KeyError: raise AttributeError(f\"No route named {name} found in route functions\")\n", " def __dir__(self): return list(self._funcs.keys())" - ], - "id": "d00984c329331d4" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "55ff40c3aa444235", + "metadata": {}, + "outputs": [], "source": [ "#| export\n", "class APIRouter:\n", @@ -3522,22 +3621,24 @@ " \"Add a websocket route at `path`\"\n", " def f(func=noop): return self.wss.append((func, f\"{self.prefix}{path}\", conn, disconn, name, middleware))\n", " return f" - ], - "id": "55ff40c3aa444235" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, - "source": "ar = APIRouter()", - "id": "66a9e4ae6be2e6e3" + "id": "66a9e4ae6be2e6e3", + "metadata": {}, + "outputs": [], + "source": [ + "ar = APIRouter()" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "1d238c64c8299999", + "metadata": {}, + "outputs": [], "source": [ "@ar(\"/hi\")\n", "def get(): return 'Hi there'\n", @@ -3560,25 +3661,25 @@ "\n", "@ar.ws(\"/ws\")\n", "def ws(self, msg:str): return f\"Message text was: {msg}\"" - ], - "id": "1d238c64c8299999" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "d8c66b9b4e73dd7f", + "metadata": {}, + "outputs": [], "source": [ "app,cli,_ = get_cli(FastHTML())\n", "ar.to_app(app)" - ], - "id": "d8c66b9b4e73dd7f" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "41b73984941e0fca", + "metadata": {}, + "outputs": [], "source": [ "assert str(yoyo) == '/yoyo'\n", "# ensure route functions are properly discoverable on `APIRouter` and `APIRouter.rt_funcs`\n", @@ -3589,14 +3690,14 @@ "with ExceptionExpected(): ar.rt_funcs.blah()\n", "# ensure any route functions named using an HTTPMethod are not discoverable via `rt_funcs`\n", "assert \"get\" not in ar.rt_funcs._funcs.keys()" - ], - "id": "41b73984941e0fca" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "c7bb0377e2cab336", + "metadata": {}, + "outputs": [], "source": [ "test_eq(cli.get('/hi').text, 'Hi there')\n", "test_eq(cli.post('/hi').text, 'Postal')\n", @@ -3610,35 +3711,37 @@ "test_r(cli, '/class-cards/abc', '{\"id\":\"abc\",\"title\":\"Foo\"}', 'patch', data={'title':'Foo'})\n", "test_eq(cli.delete('/class-cards/abc').text, 'delete abc')\n", "test_eq(CardMethods.to(id='xyz'), '/class-cards/xyz')" - ], - "id": "c7bb0377e2cab336" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "d2d806271efce6e", + "metadata": {}, + "outputs": [], "source": [ "with cli.websocket_connect('/ws') as ws:\n", " ws.send_text('{\"msg\":\"Hi!\"}')\n", " data = ws.receive_text()\n", " assert data == 'Message text was: Hi!'" - ], - "id": "d2d806271efce6e" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, - "source": "ar2 = APIRouter(\"/products\")", - "id": "609d7e4bb7e27b8d" + "id": "609d7e4bb7e27b8d", + "metadata": {}, + "outputs": [], + "source": [ + "ar2 = APIRouter(\"/products\")" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "28a985ce78b8ad79", + "metadata": {}, + "outputs": [], "source": [ "@ar2(\"/hi\")\n", "def get(): return 'Hi there'\n", @@ -3659,25 +3762,25 @@ "\n", "@ar2.ws(\"/ws\")\n", "def ws(self, msg:str): return f\"Message text was: {msg}\"" - ], - "id": "28a985ce78b8ad79" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "a8c95ca9b68b2b66", + "metadata": {}, + "outputs": [], "source": [ "app,cli,_ = get_cli(FastHTML())\n", "ar2.to_app(app)" - ], - "id": "a8c95ca9b68b2b66" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "f2c612c7d9ee1b7a", + "metadata": {}, + "outputs": [], "source": [ "assert str(yoyo) == '/products/yoyo'\n", "assert ar2.prefix == '/products'\n", @@ -3687,14 +3790,14 @@ "with ExceptionExpected(): ar2.blah()\n", "with ExceptionExpected(): ar2.rt_funcs.blah()\n", "assert \"get\" not in ar2.rt_funcs._funcs.keys()" - ], - "id": "f2c612c7d9ee1b7a" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "6884d7d5176d7c24", + "metadata": {}, + "outputs": [], "source": [ "test_eq(cli.get('/products/hi').text, 'Hi there')\n", "test_eq(cli.post('/products/hi').text, 'Postal')\n", @@ -3706,38 +3809,38 @@ "\n", "test_eq(cli.get('/products/products?id=7').text, 'product 7')\n", "test_eq(Products.to(id=7), '/products/products?id=7')" - ], - "id": "6884d7d5176d7c24" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "f13043550a77dacc", + "metadata": {}, + "outputs": [], "source": [ "with cli.websocket_connect('/products/ws') as ws:\n", " ws.send_text('{\"msg\":\"Hi!\"}')\n", " data = ws.receive_text()\n", " assert data == 'Message text was: Hi!'" - ], - "id": "f13043550a77dacc" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "1ea2020dd58c30df", + "metadata": {}, + "outputs": [], "source": [ "#| export\n", "for o in all_meths: setattr(APIRouter, o, partialmethod(APIRouter.__call__, methods=o))" - ], - "id": "1ea2020dd58c30df" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "d3019c79770fdff", + "metadata": {}, + "outputs": [], "source": [ "@ar.get\n", "def hi2(): return 'Hi there'\n", @@ -3752,28 +3855,32 @@ "def _(): return 'Hi there'\n", "@ar2.post(\"/post2\")\n", "def _(): return 'Postal'" - ], - "id": "d3019c79770fdff" + ] }, { - "metadata": {}, "cell_type": "markdown", - "source": "## Extras", - "id": "7e71158e148dcc26" + "id": "7e71158e148dcc26", + "metadata": {}, + "source": [ + "## Extras" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, - "source": "app,cli,rt = get_cli(FastHTML(secret_key='soopersecret'))", - "id": "bba4b748750fb361" + "id": "bba4b748750fb361", + "metadata": {}, + "outputs": [], + "source": [ + "app,cli,rt = get_cli(FastHTML(secret_key='soopersecret'))" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "e645895044c0f961", + "metadata": {}, + "outputs": [], "source": [ "#| export\n", "def cookie(key: str, value=\"\", max_age=None, expires=None, path=\"/\", domain=None, secure=False, httponly=False, samesite=\"lax\",):\n", @@ -3791,14 +3898,14 @@ " cookie[key][\"samesite\"] = samesite\n", " cookie_val = cookie.output(header=\"\").strip()\n", " return HttpHeader(\"set-cookie\", cookie_val)" - ], - "id": "e645895044c0f961" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "4a83a50a23d2c67c", + "metadata": {}, + "outputs": [], "source": [ "@rt(\"/setcookie\")\n", "def get(req): return cookie('now', datetime.now())\n", @@ -3809,28 +3916,28 @@ "print(cli.get('/setcookie').text)\n", "time.sleep(0.01)\n", "cli.get('/getcookie').text" - ], - "id": "4a83a50a23d2c67c" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "c094b01b787efa18", + "metadata": {}, + "outputs": [], "source": [ "#| export\n", "def reg_re_param(m, s):\n", " \"Register a Starlette URL convertor named `m` matching regex `s`\"\n", " cls = get_class(f'{m}Conv', sup=StringConvertor, regex=s)\n", " register_url_convertor(m, cls())" - ], - "id": "c094b01b787efa18" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "6747ee1f8fa10ddb", + "metadata": {}, + "outputs": [], "source": [ "#| export\n", "# Starlette doesn't have the '?', so it chomps the whole remaining URL\n", @@ -3843,14 +3950,14 @@ " \"Add a static route at URL path `prefix` with files from `static_path` and `exts` defined by `reg_re_param()`\"\n", " @self.get(f\"{prefix}{{fname:path}}.{{ext:{exts}}}\")\n", " async def get(fname:str, ext:str): return FileResponse(f'{static_path}/{fname}.{ext}')" - ], - "id": "6747ee1f8fa10ddb" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "abd47f73e0b10c81", + "metadata": {}, + "outputs": [], "source": [ "reg_re_param(\"imgext\", \"ico|gif|jpg|jpeg|webm|pdf\")\n", "\n", @@ -3858,25 +3965,25 @@ "def get(fn:str, path:str, ext:str): return f\"Getting {fn}.{ext} from /{path}\"\n", "\n", "test_r(cli, '/static/foo/jph.me.ico', 'Getting jph.me.ico from /foo/')" - ], - "id": "abd47f73e0b10c81" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "5e67b1acf340c9de", + "metadata": {}, + "outputs": [], "source": [ "app.static_route_exts()\n", "assert 'These are the source notebooks for FastHTML' in cli.get('/README.txt').text" - ], - "id": "5e67b1acf340c9de" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "f821491210017e95", + "metadata": {}, + "outputs": [], "source": [ "#| export\n", "@patch\n", @@ -3884,25 +3991,25 @@ " \"Add a static route at URL path `prefix` with files from `static_path` and single `ext` (including the '.')\"\n", " @self.get(f\"{prefix}{{fname:path}}{ext}\")\n", " async def get(fname:str): return FileResponse(f'{static_path}/{fname}{ext}')" - ], - "id": "f821491210017e95" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "572467faf76ad23e", + "metadata": {}, + "outputs": [], "source": [ "app.static_route('.md', static_path='../..')\n", "assert 'THIS FILE WAS AUTOGENERATED' in cli.get('/README.md').text" - ], - "id": "572467faf76ad23e" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "392f9abb139bb38f", + "metadata": {}, + "outputs": [], "source": [ "#| export\n", "class StaticNoCache(StaticFiles):\n", @@ -3911,14 +4018,14 @@ " resp = super().file_response(*args, **kwargs)\n", " resp.headers.setdefault(\"Cache-Control\", \"no-cache\")\n", " return resp" - ], - "id": "392f9abb139bb38f" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "a8094de91a8f6335", + "metadata": {}, + "outputs": [], "source": [ "#| export\n", "class StaticImmutable(StaticFiles):\n", @@ -3927,20 +4034,22 @@ " resp = super().file_response(*args, **kwargs)\n", " resp.headers.setdefault(\"Cache-Control\", \"public, max-age=31536000, immutable\")\n", " return resp" - ], - "id": "a8094de91a8f6335" + ] }, { - "metadata": {}, "cell_type": "markdown", - "source": "These two classes are the poles of static-file caching. `StaticNoCache` makes the browser revalidate on every use: always fresh at the cost of a conditional request each time, right for files that change under a stable URL (and for dev, where you want edits visible on reload). `StaticImmutable` promises the URL's content will never change, so the browser may cache it forever with no requests at all: only safe when a changed file gets a changed URL, which is what `vurl` or a bundler's content-hashed filenames provide.", - "id": "39634fb1dc368ff8" + "id": "39634fb1dc368ff8", + "metadata": {}, + "source": [ + "These two classes are the poles of static-file caching. `StaticNoCache` makes the browser revalidate on every use: always fresh at the cost of a conditional request each time, right for files that change under a stable URL (and for dev, where you want edits visible on reload). `StaticImmutable` promises the URL's content will never change, so the browser may cache it forever with no requests at all: only safe when a changed file gets a changed URL, which is what `vurl` or a bundler's content-hashed filenames provide." + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "8b150dc4b269a38e", + "metadata": {}, + "outputs": [], "source": [ "statd = Path(tempfile.mkdtemp())\n", "(statd/'app.css').write_text('body{}')\n", @@ -3948,14 +4057,14 @@ "stat_cli = TestClient(stat_app)\n", "test_eq(stat_cli.get('/nc/app.css').headers['cache-control'], 'no-cache')\n", "test_eq(stat_cli.get('/imm/app.css').headers['cache-control'], 'public, max-age=31536000, immutable')" - ], - "id": "8b150dc4b269a38e" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "7fffdd2e178e66d9", + "metadata": {}, + "outputs": [], "source": [ "#| export\n", "@flexicache(mtime_policy(arg=0))\n", @@ -3967,20 +4076,22 @@ " p = Path(root)/u.path.lstrip('/')\n", " q = f'{u.query}&' if u.query else ''\n", " return urlunsplit(u._replace(query=f'{q}v={_vhash(p)}'))\n" - ], - "id": "7fffdd2e178e66d9" + ] }, { - "metadata": {}, "cell_type": "markdown", - "source": "Browsers use the URL as the cache key, so a URL that changes whenever the file's contents change can be cached forever: serve the mount with `StaticImmutable` and the asset costs no requests at all until it is next edited. This is the query-param version of the content-hashed filenames that asset pipelines and bundlers produce, without the build step. The hash is cached via `flexicache` with `mtime_policy`, so a call costs one `stat` and the file is only re-read after it changes. The param is inert under `no-cache` serving, so the same links work in dev with `StaticNoCache`, where the file is rechecked on each reload.", - "id": "8e1f740dc7117a73" + "id": "8e1f740dc7117a73", + "metadata": {}, + "source": [ + "Browsers use the URL as the cache key, so a URL that changes whenever the file's contents change can be cached forever: serve the mount with `StaticImmutable` and the asset costs no requests at all until it is next edited. This is the query-param version of the content-hashed filenames that asset pipelines and bundlers produce, without the build step. The hash is cached via `flexicache` with `mtime_policy`, so a call costs one `stat` and the file is only re-read after it changes. The param is inert under `no-cache` serving, so the same links work in dev with `StaticNoCache`, where the file is rechecked on each reload." + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "3563fa848b89d640", + "metadata": {}, + "outputs": [], "source": [ "tmp = Path(tempfile.mkdtemp())\n", "(tmp/'a.css').write_text('body{}')\n", @@ -3993,26 +4104,26 @@ "(tmp/'a.css').write_text('body{color:red}')\n", "os.utime(tmp/'a.css', (time.time()+1,)*2)\n", "assert vurl('a.css', tmp) != u" - ], - "id": "3563fa848b89d640" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "fc3c4a11a7f149ed", + "metadata": {}, + "outputs": [], "source": [ "#| export\n", "from functools import wraps\n", "from inspect import signature, isawaitable" - ], - "id": "fc3c4a11a7f149ed" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "dcfbe520b21c8a06", + "metadata": {}, + "outputs": [], "source": [ "#| export\n", "def add_sig_param(f, name, typ=NoneType, kind=Parameter.KEYWORD_ONLY, default=Parameter.empty):\n", @@ -4024,14 +4135,14 @@ " f.__signature__ = sig.replace(parameters=new_params)\n", " f.__annotations__[name] = typ\n", " return f" - ], - "id": "dcfbe520b21c8a06" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "bc3a2a5a0b908c62", + "metadata": {}, + "outputs": [], "source": [ "#| export\n", "class into:\n", @@ -4054,26 +4165,30 @@ " anno = p.annotation if p.annotation is not Parameter.empty else NoneType\n", " add_sig_param(_inner, k, anno, default=p.default)\n", " return _inner" - ], - "id": "bc3a2a5a0b908c62" + ] }, { - "metadata": {}, "cell_type": "markdown", - "source": "`into` is a decorator that composes two functions: the decorated route function and an outer \"wrapper\" function (like a layout). The route's return value is passed as positional args to the wrapper. Any keyword parameters listed in `params` are added to the route's signature, so they become available as query/form parameters. This lets you write simple routes that return just their content, while the layout and its parameters are handled automatically.", - "id": "fea1234b40b7ec25" + "id": "fea1234b40b7ec25", + "metadata": {}, + "source": [ + "`into` is a decorator that composes two functions: the decorated route function and an outer \"wrapper\" function (like a layout). The route's return value is passed as positional args to the wrapper. Any keyword parameters listed in `params` are added to the route's signature, so they become available as query/form parameters. This lets you write simple routes that return just their content, while the layout and its parameters are handled automatically." + ] }, { - "metadata": {}, "cell_type": "markdown", - "source": "Here `hello` returns a single `P` tag, but `into(my_layout)` passes it into `my_layout`, which wraps it in a `Titled`. The `title` parameter is injected into `hello`'s signature so it can be set via query params.", - "id": "33fd8a5f4eec0e22" + "id": "33fd8a5f4eec0e22", + "metadata": {}, + "source": [ + "Here `hello` returns a single `P` tag, but `into(my_layout)` passes it into `my_layout`, which wraps it in a `Titled`. The `title` parameter is injected into `hello`'s signature so it can be set via query params." + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "ebedc67f3cc6c31d", + "metadata": {}, + "outputs": [], "source": [ "app,cli,rt = get_cli(FastHTML())\n", "\n", @@ -4082,50 +4197,54 @@ "@rt\n", "@into(my_layout)\n", "def hello(name:str='World'): return P(f'Hello, {name}!')" - ], - "id": "ebedc67f3cc6c31d" + ] }, { - "metadata": {}, "cell_type": "markdown", - "source": "With no query params, `name` defaults to `'World'` and `title` defaults to `'Default'` (from `my_layout`'s own default), giving us a page titled \"Default\" containing \"Hello, World!\".", - "id": "ab25de85060dd0ab" + "id": "ab25de85060dd0ab", + "metadata": {}, + "source": [ + "With no query params, `name` defaults to `'World'` and `title` defaults to `'Default'` (from `my_layout`'s own default), giving us a page titled \"Default\" containing \"Hello, World!\"." + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "777b10770ccb5990", + "metadata": {}, + "outputs": [], "source": [ "r = cli.get('/hello')\n", "assert 'Default' in r.text\n", "assert '

Hello, World!

' in r.text" - ], - "id": "777b10770ccb5990" + ] }, { - "metadata": {}, "cell_type": "markdown", - "source": "Here, both `name` and `title` are provided as query params. `name='Jeremy'` is handled by `hello` directly, while `title='Greetings'` is the injected param that gets forwarded to `my_layout`.", - "id": "ffe9179ea2cd38b3" + "id": "ffe9179ea2cd38b3", + "metadata": {}, + "source": [ + "Here, both `name` and `title` are provided as query params. `name='Jeremy'` is handled by `hello` directly, while `title='Greetings'` is the injected param that gets forwarded to `my_layout`." + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "4297bf1971b0b158", + "metadata": {}, + "outputs": [], "source": [ "r = cli.get('/hello?name=Jeremy&title=Greetings')\n", "assert 'Greetings' in r.text\n", "assert '

Hello, Jeremy!

' in r.text" - ], - "id": "4297bf1971b0b158" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "e287be9995e1d974", + "metadata": {}, + "outputs": [], "source": [ "#| export\n", "class MiddlewareBase:\n", @@ -4134,14 +4253,14 @@ " if scope[\"type\"] in (\"http\", \"websocket\"): return HTTPConnection(scope)\n", " await self._app(scope, receive, send)\n", " " - ], - "id": "e287be9995e1d974" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "abd3179c8f6dab84", + "metadata": {}, + "outputs": [], "source": [ "#| export\n", "class FtResponse:\n", @@ -4157,14 +4276,14 @@ " if not tasks: tasks = self.background\n", " headers = {**(self.headers or {}), **httphdrs}\n", " return self.cls(cts, status_code=self.status_code, headers=headers, media_type=self.media_type, background=tasks)" - ], - "id": "abd3179c8f6dab84" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "4fa7901b39ba33dd", + "metadata": {}, + "outputs": [], "source": [ "@rt('/ftr')\n", "def get():\n", @@ -4177,20 +4296,22 @@ "test_eq(r.headers['location'], '/foo/1')\n", "txt = r.text\n", "assert 'Foo' in txt and '

bar

' in txt and '' in txt" - ], - "id": "4fa7901b39ba33dd" + ] }, { - "metadata": {}, "cell_type": "markdown", - "source": "Test on a single background task:", - "id": "f671d50f1f5b6219" + "id": "f671d50f1f5b6219", + "metadata": {}, + "source": [ + "Test on a single background task:" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "dc50c01073e81407", + "metadata": {}, + "outputs": [], "source": [ "def my_slow_task():\n", " print('Starting slow task') \n", @@ -4204,34 +4325,36 @@ "\n", "test_eq(r.status_code, 200)\n", "\n" - ], - "id": "dc50c01073e81407" + ] }, { - "metadata": {}, "cell_type": "markdown", - "source": "Test multiple background tasks:", - "id": "64da62e3d30bf84c" + "id": "64da62e3d30bf84c", + "metadata": {}, + "source": [ + "Test multiple background tasks:" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "b8be74e5afbe825f", + "metadata": {}, + "outputs": [], "source": [ "def increment(amount):\n", " amount = amount/1000\n", " print(f'Sleeping for {amount}s') \n", " time.sleep(amount)\n", " print(f'Slept for {amount}s') " - ], - "id": "b8be74e5afbe825f" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "afa44a40a7afa2f5", + "metadata": {}, + "outputs": [], "source": [ "@rt\n", "def backgrounds():\n", @@ -4241,14 +4364,14 @@ "\n", "r = cli.get('/backgrounds')\n", "test_eq(r.status_code, 200)" - ], - "id": "afa44a40a7afa2f5" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "4d47edc592145db0", + "metadata": {}, + "outputs": [], "source": [ "@rt\n", "def backgrounds2():\n", @@ -4257,14 +4380,14 @@ "\n", "r = cli.get('/backgrounds2')\n", "test_eq(r.status_code, 200)" - ], - "id": "4d47edc592145db0" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "8adc71f6292c6d24", + "metadata": {}, + "outputs": [], "source": [ "@rt\n", "def backgrounds3():\n", @@ -4274,14 +4397,14 @@ "r = cli.get('/backgrounds3')\n", "test_eq(r.status_code, 200)\n", "r.json()" - ], - "id": "8adc71f6292c6d24" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "7ccb00230cdfb99e", + "metadata": {}, + "outputs": [], "source": [ "#| export\n", "def unqid(seeded=False):\n", @@ -4289,28 +4412,28 @@ " id4 = UUID(int=random.getrandbits(128), version=4) if seeded else uuid4()\n", " res = b64encode(id4.bytes)\n", " return '_' + res.decode().rstrip('=').translate(str.maketrans('+/', '_-'))" - ], - "id": "7ccb00230cdfb99e" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "e70a8dcfe4386a2e", + "metadata": {}, + "outputs": [], "source": [ "#| export\n", "def _add_ids(s):\n", " if not isinstance(s, FT): return\n", " if not getattr(s, 'id', None): s.id = unqid()\n", " for c in s.children: _add_ids(c)" - ], - "id": "e70a8dcfe4386a2e" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "6a8579524fa4bb56", + "metadata": {}, + "outputs": [], "source": [ "#| export\n", "@patch\n", @@ -4323,14 +4446,14 @@ " for o in conns.values(): await o(s)\n", " app._send = send\n", " return send" - ], - "id": "6a8579524fa4bb56" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "fcb9f273985b611e", + "metadata": {}, + "outputs": [], "source": [ "#| export\n", "devtools_loc = \"/.well-known/appspecific/com.chrome.devtools.json\"\n", @@ -4341,14 +4464,14 @@ " if not uuid: uuid = str(uuid5(NAMESPACE_URL, str(path)))\n", " @self.route(devtools_loc)\n", " def devtools(): return dict(workspace=dict(root=str(path), uuid=uuid))" - ], - "id": "fcb9f273985b611e" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "3bf9cb548b4906fd", + "metadata": {}, + "outputs": [], "source": [ "#| export\n", "@patch\n", @@ -4361,14 +4484,14 @@ " client = httpx2.AsyncClient() if asink else httpx2.Client()\n", " client.cookies.update({self.session_cookie: data.decode()})\n", " return client" - ], - "id": "3bf9cb548b4906fd" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "6942fa7012ca3ec6", + "metadata": {}, + "outputs": [], "source": [ "#| export\n", "@patch\n", @@ -4377,14 +4500,14 @@ " if not cookie or cookie == 'null': return {}\n", " unsigned = itsdangerous.TimestampSigner(self.secret_key).unsign(cookie, max_age=None)\n", " return loads(b64decode(unsigned).decode())" - ], - "id": "6942fa7012ca3ec6" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "4e64484ff03ceb38", + "metadata": {}, + "outputs": [], "source": [ "#| export\n", "@patch\n", @@ -4400,37 +4523,38 @@ " return self.app.decode_session(cookie)\n", "\n", " return FastHTMLTestClient(self, cookies=self.get_client(**kw).cookies)" - ], - "id": "4e64484ff03ceb38" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "57a7b94f1c60e334", + "metadata": {}, + "outputs": [], "source": [ "cli = app.get_testclient(auth='user1')\n", "test_eq(cli.session['auth'], 'user1')" - ], - "id": "57a7b94f1c60e334" + ] }, { - "metadata": {}, "cell_type": "markdown", - "source": "## Export -", - "id": "9bd92c051e08c337" + "id": "9bd92c051e08c337", + "metadata": {}, + "source": [ + "## Export -" + ] }, { - "metadata": {}, "cell_type": "code", - "outputs": [], "execution_count": null, + "id": "b3469b7214dd3f32", + "metadata": {}, + "outputs": [], "source": [ "#| hide\n", "import nbdev\n", "nbdev.nbdev_export()" - ], - "id": "b3469b7214dd3f32" + ] } ], "metadata": { From 232baf83e4ec1cd926429db204d6731aa6aded8b Mon Sep 17 00:00:00 2001 From: Renato Gomes Damas Date: Wed, 21 Oct 2026 12:43:59 -0300 Subject: [PATCH 14/14] refactor: update request parameter aliases to camelCase and arbitrary. --- tests/test_alias.py | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/tests/test_alias.py b/tests/test_alias.py index 059fe82b..8fd4138b 100644 --- a/tests/test_alias.py +++ b/tests/test_alias.py @@ -6,37 +6,37 @@ cli = TestClient(app) @rt("/query") -def get(user_id: Annotated[str, Alias("user-id")]): return f"q:{user_id}" +def get(user_id: Annotated[str, Alias("userId")]): return f"q:{user_id}" @rt("/form", methods=["post"]) -def post(user_id: Annotated[str, Alias("user-id")]): return f"f:{user_id}" +def post(user_id: Annotated[str, Alias("userId")]): return f"f:{user_id}" -@rt("/path/{item_id}") -def get(item_id: Annotated[int, Alias("item_id")]): return f"p:{item_id}" +@rt("/path/{itemId}") +def get(item_id: Annotated[int, Alias("itemId")]): return f"p:{item_id}" @rt("/header") -def get(x_api_key: Annotated[str, Alias("X-Api-Key")]): return f"h:{x_api_key}" +def get(x_api_key_hdr: Annotated[str, Alias("X-Api-Key")]): return f"h:{x_api_key_hdr}" @rt("/cookie") -def get(req, session_id: Annotated[str, Alias("session-id")]): return f"c:{session_id}" +def get(req, sid_cookie: Annotated[str, Alias("session-id")]): return f"c:{sid_cookie}" @rt("/int") -def get(count: Annotated[int, Alias("the-count")]): return f"i:{count + 1}" +def get(count: Annotated[int, Alias("theCount")]): return f"i:{count + 1}" @rt("/plain") def get(user_id: str): return f"plain:{user_id}" @rt("/missing") -def get(user_id: Annotated[str, Alias("user-id")]): return user_id +def get(user_id: Annotated[str, Alias("userId")]): return user_id -def test_query_alias(): assert cli.get('/query?user-id=abc').text == 'q:abc' -def test_form_alias(): assert cli.post('/form', data={'user-id': 'abc'}).text == 'f:abc' +def test_query_alias(): assert cli.get('/query?userId=abc').text == 'q:abc' +def test_form_alias(): assert cli.post('/form', data={'userId': 'abc'}).text == 'f:abc' def test_path_alias(): assert cli.get('/path/7').text == 'p:7' def test_header_alias(): assert cli.get('/header', headers={'X-Api-Key': 'k1'}).text == 'h:k1' def test_cookie_alias(): assert cli.get('/cookie', cookies={'session-id': 's1'}).text == 'c:s1' -def test_int_alias(): assert cli.get('/int?the-count=4').text == 'i:5' -def test_plain_unchanged(): assert cli.get('/plain?user_id=z').text == 'plain:z' -def test_snake_name_not_used_for_alias(): assert cli.get('/query?user_id=abc').status_code == 400 +def test_int_alias(): assert cli.get('/int?theCount=4').text == 'i:5' +def test_plain_unchanged(): assert cli.get('/plain?user-id=z').text == 'plain:z' +def test_alias_is_case_sensitive(): assert cli.get('/query?userID=abc').status_code == 400 def test_missing_message_uses_alias(): r = cli.get('/missing') - assert r.status_code == 400 and 'Missing required field: user-id' in r.text + assert r.status_code == 400 and 'Missing required field: userId' in r.text