diff --git a/fasthtml/_modidx.py b/fasthtml/_modidx.py index 9748eec4..49cceb3f 100644 --- a/fasthtml/_modidx.py +++ b/fasthtml/_modidx.py @@ -30,6 +30,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 65a1ac11..609b8068 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, 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 @@ -48,13 +48,13 @@ 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', + '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', 'BearerSessionMiddleware', '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 +# %% ../nbs/api/00_core.ipynb #c9ebcfc30a1f800 import json,uuid,inspect,types,asyncio,inspect,random,contextlib,itsdangerous,hashlib,signal,subprocess from uuid import uuid5, NAMESPACE_URL @@ -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 @@ -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 #812ef9183ad0b657 def _params(f): return signature_ex(f, True).parameters empty = Parameter.empty -# %% ../nbs/api/00_core.ipynb #e68a76c9 +# %% ../nbs/api/00_core.ipynb #c5028c09a628533 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 #160b6878e8a6a74d 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 #31fb5e7526f55d26 htmx_hdrs = dict( boosted="HX-Boosted", current_url="HX-Current-URL", @@ -129,13 +129,13 @@ def _get_htmx(h): res = {k:_get_header(h, v) for k,v in htmx_hdrs.items()} return HtmxHeaders(**res) -# %% ../nbs/api/00_core.ipynb #1d53e8e7 +# %% ../nbs/api/00_core.ipynb #6a06097681bcd6a6 def _mk_list(t, v): return [t(o) for o in listify(v)] -# %% ../nbs/api/00_core.ipynb #5ab74473 +# %% ../nbs/api/00_core.ipynb #12f93b7aa5424194 fh_cfg = AttrDict(indent=True) -# %% ../nbs/api/00_core.ipynb #88d12e68 +# %% ../nbs/api/00_core.ipynb #58660171446e4348 _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): @@ -143,7 +143,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 #a6c4d5dec9a11382 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) @@ -156,7 +156,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 #10852e6f03bb7231 def _form_arg(k, v, d): "Get type by accessing key `k` from `d`, and use to cast `v`" if v is None: return @@ -166,35 +166,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 #b40f180dae734a89 @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 #3cf407bbe6d72fce 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 #2cf50288f5a348f @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 #922afe94af9a5100 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 #5a1fa453f1caafa7 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 #84fe8f035ba3132d 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) @@ -202,16 +202,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 #ba55a6ab2bf79e81 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 #7154b82a09979e0a DEF_MAXPART = 100*1024*1024 -# %% ../nbs/api/00_core.ipynb #42c9cea0 +# %% ../nbs/api/00_core.ipynb #1f95924092f9c33d 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", "") @@ -230,7 +230,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 #8e8b9056b2f3a099 async def _from_body(conn, p, data): "Create an instance of the annotated type from pre-parsed `data`" anno = p.annotation @@ -246,7 +246,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 #a73dc9076461a6a9 class ApiReturn: "Request param: call with browser and API responses; returns kwargs as JSON if the client accepts `application/json`, else `norm`" @classmethod @@ -255,7 +255,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 #c835e81d6e4f5efd class JSONResponse(JSONResponseOrig): "Same as starlette's version, but auto-stringifies non serializable types" def render(self, content:Any)->bytes: @@ -264,9 +264,20 @@ 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 #4e1d265576d2d438 +@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): @@ -276,54 +287,54 @@ 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) + 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(arg, None) - if res in (empty,None): res = conn.cookies.get(arg, None) - if res in (empty,None): res = _get_header(hdrs, snake2hyphens(arg)) - 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 = _get_header(hdrs, snake2hyphens(key)) + 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: 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 #40f862f356ae9ebb 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 #f88072f39efb683e 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 #2891fffa291ffaa9 def flat_xt(lst): "Flatten lists" result = [] @@ -333,23 +344,23 @@ def flat_xt(lst): else: result.append(item) return tuple(result) -# %% ../nbs/api/00_core.ipynb #aacff5ac +# %% ../nbs/api/00_core.ipynb #7f97f41c7180179a 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 #24171b42d8ed41ee 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 #dc78b1c31eb67d83 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 #29df49dfbdbeab89 async def _send_ws(ws, resp): if not resp: return res = to_xml(resp, indent=fh_cfg.indent) @@ -377,12 +388,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 #83fa302372e0e042 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 #f588429f00c732e7 def signal_shutdown(): "Return an `asyncio.Event` set when uvicorn receives a shutdown signal" from uvicorn.main import Server @@ -394,21 +405,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 #1537735647b1227f 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 #3004b7d11797405c 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 #e9de9e161764947b from starlette.convertors import StringConvertor -# %% ../nbs/api/00_core.ipynb #a27adc1e +# %% ../nbs/api/00_core.ipynb #b9bb3ffe99344740 StringConvertor.regex = "[^/]*" # `+` replaced with `*` @patch @@ -418,13 +429,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 #cccf24a4868dd227 @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 #535fa019103e6f9d _verbs = dict(get='hx-get', post='hx-post', put='hx-put', delete='hx-delete', patch='hx-patch', link='href') def _url_for(req, t): @@ -450,10 +461,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 #69d2044af9aa17d4 _iter_typs = (tuple,list,map,filter,range,types.GeneratorType) -# %% ../nbs/api/00_core.ipynb #a407dc0e +# %% ../nbs/api/00_core.ipynb #fecf15a81dec5af7 def flat_tuple(o): "Flatten nested iterables into a single tuple" result = [] @@ -464,12 +475,12 @@ def flat_tuple(o): else: result.append(item) return tuple(result) -# %% ../nbs/api/00_core.ipynb #d36402e6 +# %% ../nbs/api/00_core.ipynb #f50bb04220c638a9 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 #d7ae82dfa40eb3f2 def respond(req, heads, bdy): "Default FT response creation function" body_wrap = getattr(req, 'body_wrap', noop_body) @@ -478,13 +489,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 #a3674bc161b39a23 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 #3ee9a5fb4b7929a3 def _part_resp(req, resp): "Partition response into HTTP headers, background tasks, and content" resp = flat_tuple(resp) @@ -501,7 +512,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 #c69f2a6c99eeeb1e def _canonical(req): if not req.app.canonical: return [] url = str(getattr(req, 'canonical', req.url)).replace('http://', 'https://', 1) @@ -517,12 +528,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 #3651675357475aa2 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 #74898954bcd20abe def _resp(req, resp, cls=empty, status_code=200): "Create appropriate HTTP response from request and response data" if resp is None: resp='' @@ -542,7 +553,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 #4b0745e3157bccbb class Redirect: "Use HTMX or Starlette RedirectResponse as required to redirect to `loc`" def __init__(self, loc): self.loc = loc @@ -550,13 +561,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 #147cb69ae182351c 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 #f7f626a00aad8476 # chkstyle: skip htmx_exts = { "morph": "https://cdn.jsdelivr.net/npm/idiomorph@0.7.3/dist/idiomorph-ext.min.js", @@ -576,7 +587,7 @@ async def _wrap_call(f, req, params): "multipart": "https://cdn.jsdelivr.net/npm/htmx.org@4.0.1/dist/ext/hx-multipart.min.js" } -# %% ../nbs/api/00_core.ipynb #60cb52ea +# %% ../nbs/api/00_core.ipynb #59076ca3b38a5fba 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.1/dist/htmx.min.js") fhjsscr = Script(src="https://cdn.jsdelivr.net/gh/answerdotai/fasthtml-js@1.0.13/fasthtml.js") @@ -585,7 +596,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 #3f9e66d883079f28 def get_key(key=None, fname='.sesskey'): "Get session key from `key` param or read/create from file `fname`" if key: return key @@ -595,12 +606,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 #7eb35d0263b7da5a 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 #87cbf1149a207d27 def _wrap_ex(f, status_code, hdrs, ftrs, htmlkw, bodykw, body_wrap): "Wrap exception handler with FastHTML request processing" async def _f(req, exc): @@ -612,7 +623,7 @@ async def _f(req, exc): return _resp(req, res, status_code=code) return _f -# %% ../nbs/api/00_core.ipynb #bc323fd4 +# %% ../nbs/api/00_core.ipynb #f772e4bd5cb60fe2 def qp(p:str, **kw) -> str: "Add parameters kw to path p" def _sub(m): @@ -624,12 +635,12 @@ 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 #7617757c40c72efe def def_hdrs(htmx=True, htmx4=False, surreal=True): "Default headers for a FastHTML app" hdrs = [] if surreal: hdrs = [surrsrc,scopesrc] + hdrs - if htmx and htmx4: + if htmx and htmx4: # metaCharacter="-" makes htmx4 use dashes instead of colons meta_cfg = Meta(name="htmx-config", content=json.dumps({"metaCharacter": "-"})) hdrs = [meta_cfg, htmx4src,fhjsscr] + hdrs @@ -637,7 +648,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 #77869926479cdf46 cors_allow = Middleware(CORSMiddleware, allow_credentials=True, allow_origins=['*'], allow_methods=['*'], allow_headers=['*']) iframe_scr = Script(NotStr(""" @@ -663,7 +674,7 @@ def def_hdrs(htmx=True, htmx4=False, surreal=True): """)) -# %% ../nbs/api/00_core.ipynb #17ced9a3 +# %% ../nbs/api/00_core.ipynb #f127a504464b0eb5 class _LifespanCtx: def __init__(self, gen): self.gen = gen async def __aenter__(self): return await anext(self.gen) @@ -709,7 +720,7 @@ async def __call__(self, scope, receive, send): [(b'cookie', cookie.encode('latin-1'))]) await super().__call__(scope, receive, send) -# %% ../nbs/api/00_core.ipynb #3327a1e9 +# %% ../nbs/api/00_core.ipynb #c186654600ae903f 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, @@ -748,7 +759,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 #4d43cd70f3e6cd75 class HostRoute(Route): "Route with optional host-header constraint using Starlette's {param} pattern syntax" def __init__(self, path, endpoint, *, host=None, **kwargs): @@ -766,7 +777,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 #d100258e169dbbc7 @patch def add_route(self:FastHTML, route): "Add or replace a route in the FastHTML app" @@ -778,10 +789,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 #d7af2cc5decee07 all_meths = 'get post put delete patch head trace options'.split() -# %% ../nbs/api/00_core.ipynb #26b147ba +# %% ../nbs/api/00_core.ipynb #e025b784db90b0f0 @patch def _endp(self:FastHTML, f, body_wrap, before:Optional[Callable|tuple]=None): "Create endpoint wrapper with before/after middleware processing" @@ -810,7 +821,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 #3213bbd6e68c6eca @patch def _add_ws(self:FastHTML, func, path, conn, disconn, name, middleware): "Add websocket route to FastHTML app" @@ -820,20 +831,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 #b04007ab3b0564b7 @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 #f327ebcd11de3159 @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 #73a6816c7fc2a48e def _mk_locfunc(f, p, app=None): "Create a location function wrapper with route path and to() method" class _lf: @@ -847,12 +858,12 @@ def __str__(self): return p return _lf() -# %% ../nbs/api/00_core.ipynb #d2ecc738 +# %% ../nbs/api/00_core.ipynb #106d9bbb8cb464d1 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 #bf1de7b1007ef27a @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`" @@ -864,7 +875,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 #2c1c95dde3ab364b def _route_pn(func, path, name): "Infer route name/function name/path from an endpoint or endpoint class" fn = nested_name(func) @@ -889,7 +900,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 #1c4c8d49e989e7c7 @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`" @@ -899,14 +910,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 #bb214bd0b004e83c @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 #306333c1e9460062 def serve( appname=None, # Name of the module app='app', # App instance to be served @@ -932,14 +943,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 #30c5cb0a53a38c92 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 #157c183cd8bd0475 async def _wait_disconnect(req): while (await req.receive())["type"] != "http.disconnect": pass @@ -954,7 +965,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 #63f31cbcd3a2cb7e def cancel_on_disconnect( f=None, # Async route handler to wrap *, @@ -968,7 +979,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 #778e281e884f69a4 class Client: "A simple httpx ASGI client that doesn't require `async`" def __init__(self, app, url="http://testserver"): @@ -981,7 +992,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 #f1c11644b46e01d1 class RouteFuncs: "Attr-access store of named route functions (HTTP verb names excluded)" def __init__(self): super().__setattr__('_funcs', {}) @@ -992,7 +1003,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 #890c6b36806499f6 class APIRouter: "Add routes to an app" def __init__(self, prefix:str|None=None, body_wrap=noop_body): @@ -1032,10 +1043,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 #c01860fe7517722d for o in all_meths: setattr(APIRouter, o, partialmethod(APIRouter.__call__, methods=o)) -# %% ../nbs/api/00_core.ipynb #e518de83 +# %% ../nbs/api/00_core.ipynb #6d41906f21e2e5bb 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() @@ -1052,13 +1063,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 #acfb97d2b978356 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 #b5aea8aaa5b024d2 # 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() @@ -1070,14 +1081,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 #179c165cf2d70fa0 @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 #df8649e9ff8a4862 class StaticNoCache(StaticFiles): "StaticFiles that sends `Cache-Control: no-cache`, so browsers revalidate on every use" def file_response(self, *args, **kwargs): @@ -1085,7 +1096,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 #b4b419bffadedf7c 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): @@ -1093,7 +1104,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 #f650d7d18b386925 @flexicache(mtime_policy(arg=0)) def _vhash(p): return hashlib.blake2b(p.read_bytes(), digest_size=4).hexdigest() @@ -1105,11 +1116,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 #e336fb23b6a4348 from functools import wraps from inspect import signature, isawaitable -# %% ../nbs/api/00_core.ipynb #7eed23b7 +# %% ../nbs/api/00_core.ipynb #fffed22d52dd5db8 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) @@ -1120,7 +1131,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 #2908db7385793cc5 class into: "Decorator to pass a route's return value into `func`, with keyword params added to the route signature" def __init__(self, func): @@ -1142,7 +1153,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 #7f46d6e01ce2773c class MiddlewareBase: "Base for middleware: passes non-http/ws scopes through, else returns the `HTTPConnection`" async def __call__(self, scope, receive, send) -> None: @@ -1150,7 +1161,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 #bd853c5a477ed976 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): @@ -1165,20 +1176,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 #78bc2834a3ea6cda 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 #7c977335a4ba289b 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 #1a6b71aa1ba2e789 @patch def setup_ws(app:FastHTML, f=noop): conns = {} @@ -1190,7 +1201,7 @@ async def send(s): app._send = send return send -# %% ../nbs/api/00_core.ipynb #a8a91edd +# %% ../nbs/api/00_core.ipynb #699ee6943e1c8ac6 devtools_loc = "/.well-known/appspecific/com.chrome.devtools.json" @patch @@ -1200,7 +1211,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 #75158856bbe1f5bf @patch def get_client(self:FastHTML, asink=False, **kw): "Get an httpx client with session cookes set from `**kw`" @@ -1212,7 +1223,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 #bb041161d82c7ec8 @patch def decode_session(self:FastHTML, cookie): "Decode a signed session cookie" @@ -1220,7 +1231,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 #8e3efceea8c5b4e9 @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 df4465b5..ac878ae2 100644 --- a/nbs/api/00_core.ipynb +++ b/nbs/api/00_core.ipynb @@ -3,7 +3,7 @@ { "cell_type": "code", "execution_count": null, - "id": "fa505c58", + "id": "6f182d9b04f883f8", "metadata": {}, "outputs": [], "source": [ @@ -12,7 +12,7 @@ }, { "cell_type": "markdown", - "id": "2161d9b5", + "id": "e95bb035875ca78e", "metadata": {}, "source": [ "# Core\n", @@ -21,7 +21,7 @@ }, { "cell_type": "markdown", - "id": "1f8f308f", + "id": "e677d55d4ab83fe3", "metadata": {}, "source": [ "#| export\n", @@ -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. 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", @@ -68,7 +68,7 @@ }, { "cell_type": "markdown", - "id": "46e2e6e8", + "id": "903f740e786d72ef", "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/)." @@ -76,7 +76,7 @@ }, { "cell_type": "markdown", - "id": "568b20cd", + "id": "54449bc2ec290078", "metadata": {}, "source": [ "## Imports and utils" @@ -85,7 +85,7 @@ { "cell_type": "code", "execution_count": null, - "id": "23503b9e", + "id": "c9ebcfc30a1f800", "metadata": {}, "outputs": [], "source": [ @@ -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", @@ -121,7 +121,7 @@ { "cell_type": "code", "execution_count": null, - "id": "7f5d0a72", + "id": "3b3325d761ae38f0", "metadata": {}, "outputs": [], "source": [ @@ -142,7 +142,7 @@ { "cell_type": "code", "execution_count": null, - "id": "19d3f2a7", + "id": "812ef9183ad0b657", "metadata": {}, "outputs": [], "source": [ @@ -154,7 +154,7 @@ }, { "cell_type": "markdown", - "id": "19ffa7e0", + "id": "b3fe417531ab5791", "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." @@ -163,7 +163,7 @@ { "cell_type": "code", "execution_count": null, - "id": "e68a76c9", + "id": "c5028c09a628533", "metadata": {}, "outputs": [], "source": [ @@ -176,20 +176,9 @@ { "cell_type": "code", "execution_count": null, - "id": "5331a3e7", + "id": "99c729bebfde58a0", "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "datetime.datetime(2026, 10, 30, 14, 0)" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], + "outputs": [], "source": [ "parsed_date('2pm')" ] @@ -197,20 +186,9 @@ { "cell_type": "code", "execution_count": null, - "id": "c40c9071", + "id": "26368c9d9e077c03", "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "True" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], + "outputs": [], "source": [ "isinstance(date.fromtimestamp(0), date)" ] @@ -218,7 +196,7 @@ { "cell_type": "code", "execution_count": null, - "id": "7c820373", + "id": "160b6878e8a6a74d", "metadata": {}, "outputs": [], "source": [ @@ -232,20 +210,9 @@ { "cell_type": "code", "execution_count": null, - "id": "442a5aac", + "id": "55b7ce87ad73f8fa", "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "'Snake-Case'" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], + "outputs": [], "source": [ "snake2hyphens(\"snake_case\")" ] @@ -253,7 +220,7 @@ { "cell_type": "code", "execution_count": null, - "id": "25f3b8f8", + "id": "31fb5e7526f55d26", "metadata": {}, "outputs": [], "source": [ @@ -292,7 +259,7 @@ { "cell_type": "code", "execution_count": null, - "id": "5b4b5d95", + "id": "51788957f6661b97", "metadata": {}, "outputs": [], "source": [ @@ -307,20 +274,9 @@ { "cell_type": "code", "execution_count": null, - "id": "36e2cac0", + "id": "1e158eb13c8fd937", "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" - } - ], + "outputs": [], "source": [ "h = test_request(headers=Headers({'HX-Request':'1'}))\n", "_get_htmx(h.headers)" @@ -329,7 +285,7 @@ { "cell_type": "code", "execution_count": null, - "id": "1d53e8e7", + "id": "6a06097681bcd6a6", "metadata": {}, "outputs": [], "source": [ @@ -339,7 +295,7 @@ }, { "cell_type": "markdown", - "id": "ef18f76b", + "id": "afbdcd4c35b7a02", "metadata": {}, "source": [ "## Request and response" @@ -348,7 +304,7 @@ { "cell_type": "code", "execution_count": null, - "id": "5ab74473", + "id": "12f93b7aa5424194", "metadata": {}, "outputs": [], "source": [ @@ -359,7 +315,7 @@ { "cell_type": "code", "execution_count": null, - "id": "88d12e68", + "id": "58660171446e4348", "metadata": {}, "outputs": [], "source": [ @@ -375,7 +331,7 @@ { "cell_type": "code", "execution_count": null, - "id": "0afb520c", + "id": "a6c4d5dec9a11382", "metadata": {}, "outputs": [], "source": [ @@ -396,7 +352,7 @@ { "cell_type": "code", "execution_count": null, - "id": "95b1f5c9", + "id": "1a9b7e8d12d23dda", "metadata": {}, "outputs": [], "source": [ @@ -417,7 +373,7 @@ { "cell_type": "code", "execution_count": null, - "id": "c58ccadb", + "id": "10852e6f03bb7231", "metadata": {}, "outputs": [], "source": [ @@ -435,7 +391,7 @@ { "cell_type": "code", "execution_count": null, - "id": "59757d76", + "id": "45caa12c914c6cff", "metadata": {}, "outputs": [], "source": [ @@ -448,7 +404,7 @@ { "cell_type": "code", "execution_count": null, - "id": "5fc04751", + "id": "b40f180dae734a89", "metadata": {}, "outputs": [], "source": [ @@ -462,7 +418,7 @@ { "cell_type": "code", "execution_count": null, - "id": "94e18161", + "id": "3cf407bbe6d72fce", "metadata": {}, "outputs": [], "source": [ @@ -476,20 +432,9 @@ { "cell_type": "code", "execution_count": null, - "id": "592d6c8e", + "id": "cee63b8f24b0c0a8", "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "'HX-Trigger-After-Settle'" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], + "outputs": [], "source": [ "_to_htmx_header('trigger_after_settle')" ] @@ -497,7 +442,7 @@ { "cell_type": "code", "execution_count": null, - "id": "f6a2e62e", + "id": "2cf50288f5a348f", "metadata": {}, "outputs": [], "source": [ @@ -512,20 +457,9 @@ { "cell_type": "code", "execution_count": null, - "id": "e89857eb", + "id": "bc360792aa6c87a4", "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "HttpHeader(k='HX-Trigger-After-Settle', v='hi')" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], + "outputs": [], "source": [ "HtmxResponseHeaders(trigger_after_settle='hi')" ] @@ -533,7 +467,7 @@ { "cell_type": "code", "execution_count": null, - "id": "56cc589f", + "id": "922afe94af9a5100", "metadata": {}, "outputs": [], "source": [ @@ -547,20 +481,9 @@ { "cell_type": "code", "execution_count": null, - "id": "5453a684", + "id": "725b8e6b277f380", "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "{'a': int, 'b': str}" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], + "outputs": [], "source": [ "@dataclass\n", "class Foo: a:int; b:str\n", @@ -570,20 +493,9 @@ { "cell_type": "code", "execution_count": null, - "id": "bcad3a5a", + "id": "2ce7a7675a658c1d", "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "{'x': str, 'y': str}" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], + "outputs": [], "source": [ "Point = namedtuple('Point', ['x', 'y'])\n", "_annotations(Point)" @@ -592,7 +504,7 @@ { "cell_type": "code", "execution_count": null, - "id": "cb4ed4aa", + "id": "5a1fa453f1caafa7", "metadata": {}, "outputs": [], "source": [ @@ -603,7 +515,7 @@ { "cell_type": "code", "execution_count": null, - "id": "ffdde66f", + "id": "84fe8f035ba3132d", "metadata": {}, "outputs": [], "source": [ @@ -619,7 +531,7 @@ { "cell_type": "code", "execution_count": null, - "id": "5fe74444", + "id": "ba55a6ab2bf79e81", "metadata": {}, "outputs": [], "source": [ @@ -633,7 +545,7 @@ { "cell_type": "code", "execution_count": null, - "id": "cf80ea34", + "id": "1aece2ed47f3ede8", "metadata": {}, "outputs": [], "source": [ @@ -647,7 +559,7 @@ { "cell_type": "code", "execution_count": null, - "id": "8899bc0a", + "id": "7154b82a09979e0a", "metadata": {}, "outputs": [], "source": [ @@ -658,7 +570,7 @@ { "cell_type": "code", "execution_count": null, - "id": "42c9cea0", + "id": "1f95924092f9c33d", "metadata": {}, "outputs": [], "source": [ @@ -684,7 +596,7 @@ }, { "cell_type": "markdown", - "id": "437263a3", + "id": "9d81d7e43a0b2f5a", "metadata": {}, "source": [ "Use the special `__from_request__` class method for custom creation:" @@ -693,7 +605,7 @@ { "cell_type": "code", "execution_count": null, - "id": "8235f17f", + "id": "c6711a4184912f33", "metadata": {}, "outputs": [], "source": [ @@ -707,7 +619,7 @@ { "cell_type": "code", "execution_count": null, - "id": "a4873835", + "id": "d96b2e3f51684700", "metadata": {}, "outputs": [], "source": [ @@ -721,7 +633,7 @@ { "cell_type": "code", "execution_count": null, - "id": "0caedd04", + "id": "8e8b9056b2f3a099", "metadata": {}, "outputs": [], "source": [ @@ -745,7 +657,7 @@ { "cell_type": "code", "execution_count": null, - "id": "88b6da3f", + "id": "a73dc9076461a6a9", "metadata": {}, "outputs": [], "source": [ @@ -761,7 +673,7 @@ }, { "cell_type": "markdown", - "id": "abfc3145", + "id": "8e96fdc9a5ccb8d3", "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." @@ -770,7 +682,7 @@ { "cell_type": "code", "execution_count": null, - "id": "7cc39ba9", + "id": "c835e81d6e4f5efd", "metadata": {}, "outputs": [], "source": [ @@ -786,17 +698,9 @@ { "cell_type": "code", "execution_count": null, - "id": "2a8b10f4", + "id": "eda3a26f75c80269", "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "{'k': 'value1', 'v': 'value3'}\n" - ] - } - ], + "outputs": [], "source": [ "async def f(req):\n", " def _f(p:HttpHeader): ...\n", @@ -815,7 +719,7 @@ { "cell_type": "code", "execution_count": null, - "id": "301e06eb", + "id": "7a4287b3c6be8e7f", "metadata": {}, "outputs": [], "source": [ @@ -831,7 +735,7 @@ }, { "cell_type": "markdown", - "id": "18a9e366", + "id": "8a6253774ec8c5ae", "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:" @@ -840,27 +744,9 @@ { "cell_type": "code", "execution_count": null, - "id": "28bfbbc1", + "id": "a7b9836c3b2a4631", "metadata": {}, - "outputs": [ - { - "name": "stderr", - "output_type": "stream", - "text": [ - "Did not find CR at end of boundary (5)\n" - ] - }, - { - "data": { - "text/plain": [ - "'Invalid multipart data.'" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], + "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", @@ -870,7 +756,7 @@ }, { "cell_type": "markdown", - "id": "6103784b", + "id": "2560bc0f911905f", "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:" @@ -879,20 +765,9 @@ { "cell_type": "code", "execution_count": null, - "id": "2aaa8fbe", + "id": "1f3997722ada8861", "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "'Invalid JSON body'" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], + "outputs": [], "source": [ "res = client.post('/', json=[1,2])\n", "test_eq(res.status_code, 400)\n", @@ -904,20 +779,9 @@ { "cell_type": "code", "execution_count": null, - "id": "9246153f", + "id": "ad6e689226231537", "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "\"['1', '2']\"" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], + "outputs": [], "source": [ "async def f(req): return Response(str(req.query_params.getlist('x')))\n", "client = TestClient(Starlette(routes=[Route('/', f, methods=['GET'])]))\n", @@ -927,13 +791,24 @@ { "cell_type": "code", "execution_count": null, - "id": "5fa96e3a", + "id": "4e1d265576d2d438", "metadata": {}, "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", @@ -943,37 +818,37 @@ " 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(arg, None)\n", - " if res in (empty,None): res = conn.cookies.get(arg, None)\n", - " if res in (empty,None): res = _get_header(hdrs, snake2hyphens(arg))\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", + " 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 = _get_header(hdrs, snake2hyphens(key))\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", @@ -984,7 +859,7 @@ { "cell_type": "code", "execution_count": null, - "id": "bf42edad", + "id": "40f862f356ae9ebb", "metadata": {}, "outputs": [], "source": [ @@ -997,20 +872,9 @@ { "cell_type": "code", "execution_count": null, - "id": "0ac66d98", + "id": "333f3e9cee44b116", "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "Foo(d={'a': 1})" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], + "outputs": [], "source": [ "data = form2dict(await parse_form(req))\n", "await _from_body(req, p, data)" @@ -1019,7 +883,7 @@ { "cell_type": "code", "execution_count": null, - "id": "090f1f0f", + "id": "f88072f39efb683e", "metadata": {}, "outputs": [], "source": [ @@ -1032,17 +896,9 @@ { "cell_type": "code", "execution_count": null, - "id": "26df5218", + "id": "95095f35a5e490ba", "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "ok body=19\n" - ] - } - ], + "outputs": [], "source": [ "def g(test_val:int=0, item:HttpHeader=None, htmx:HtmxHeaders=None, api:ApiReturn=None): ...\n", "\n", @@ -1060,17 +916,9 @@ { "cell_type": "code", "execution_count": null, - "id": "bf945ee8", + "id": "344a41cd35813e62", "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "{'req': , 'this': , 'a': '1', 'b': HttpHeader(k='value1', v='value3'), 'state': }\n" - ] - } - ], + "outputs": [], "source": [ "def g(req, this:Starlette, a:str, b:HttpHeader, state): ...\n", "\n", @@ -1086,17 +934,9 @@ { "cell_type": "code", "execution_count": null, - "id": "a3ded5ec", + "id": "21f4350b27bb8574", "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "{'req': , 'this': , 'a': '1', 'b': HttpHeader(k='value1', v='value3')}\n" - ] - } - ], + "outputs": [], "source": [ "def g(req, this:Starlette, a:str, b:HttpHeader): ...\n", "\n", @@ -1112,20 +952,9 @@ { "cell_type": "code", "execution_count": null, - "id": "0e7601fe", + "id": "44a9d5dfcd36e22e", "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "\"Bar(accept='application/json')\"" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], + "outputs": [], "source": [ "class Bar(BasicRepr):\n", " @classmethod\n", @@ -1144,7 +973,7 @@ }, { "cell_type": "markdown", - "id": "34066c89", + "id": "656da34bb96217da", "metadata": {}, "source": [ "**Missing Request Params**" @@ -1152,7 +981,7 @@ }, { "cell_type": "markdown", - "id": "06259883", + "id": "56c21769fa8e07a2", "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." @@ -1161,17 +990,9 @@ { "cell_type": "code", "execution_count": null, - "id": "c369a89c", + "id": "a6c0d46f27cd6a59", "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "{'req': , 'this': , 'a': ''}\n" - ] - } - ], + "outputs": [], "source": [ "def g(req, this:Starlette, a:str=''): ...\n", "\n", @@ -1186,7 +1007,7 @@ }, { "cell_type": "markdown", - "id": "35b68f4f", + "id": "be49f689111388d3", "metadata": {}, "source": [ "If we remove the default value and re-run the request, we should get the following error `Missing required field: a`." @@ -1195,17 +1016,9 @@ { "cell_type": "code", "execution_count": null, - "id": "b33b43a7", + "id": "e2361d7c09c9dc0e", "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Missing required field: a\n" - ] - } - ], + "outputs": [], "source": [ "def g(req, this:Starlette, a:str): ...\n", "\n", @@ -1221,7 +1034,7 @@ { "cell_type": "code", "execution_count": null, - "id": "7a661bfa", + "id": "2891fffa291ffaa9", "metadata": {}, "outputs": [], "source": [ @@ -1239,7 +1052,7 @@ { "cell_type": "code", "execution_count": null, - "id": "2ee5adf1", + "id": "e346519dcdc20f65", "metadata": {}, "outputs": [], "source": [ @@ -1251,7 +1064,7 @@ { "cell_type": "code", "execution_count": null, - "id": "aacff5ac", + "id": "7f97f41c7180179a", "metadata": {}, "outputs": [], "source": [ @@ -1265,7 +1078,7 @@ { "cell_type": "code", "execution_count": null, - "id": "78c3c357", + "id": "24171b42d8ed41ee", "metadata": {}, "outputs": [], "source": [ @@ -1277,7 +1090,7 @@ { "cell_type": "code", "execution_count": null, - "id": "c995850c", + "id": "1960a31440d760ef", "metadata": {}, "outputs": [], "source": [ @@ -1287,7 +1100,7 @@ }, { "cell_type": "markdown", - "id": "079a3215", + "id": "1a5aafad50bad413", "metadata": {}, "source": [ "## Websockets / SSE" @@ -1296,7 +1109,7 @@ { "cell_type": "code", "execution_count": null, - "id": "ad0f0e87", + "id": "dc78b1c31eb67d83", "metadata": {}, "outputs": [], "source": [ @@ -1310,7 +1123,7 @@ { "cell_type": "code", "execution_count": null, - "id": "dcc15129", + "id": "29df49dfbdbeab89", "metadata": {}, "outputs": [], "source": [ @@ -1346,7 +1159,7 @@ { "cell_type": "code", "execution_count": null, - "id": "983bcfe2", + "id": "236148ae9145c814", "metadata": {}, "outputs": [], "source": [ @@ -1362,7 +1175,7 @@ { "cell_type": "code", "execution_count": null, - "id": "bda2e425", + "id": "9ab2cb1c438fe4b9", "metadata": {}, "outputs": [], "source": [ @@ -1377,7 +1190,7 @@ { "cell_type": "code", "execution_count": null, - "id": "5b0e7677", + "id": "83fa302372e0e042", "metadata": {}, "outputs": [], "source": [ @@ -1390,7 +1203,7 @@ { "cell_type": "code", "execution_count": null, - "id": "0dd0a414", + "id": "f588429f00c732e7", "metadata": {}, "outputs": [], "source": [ @@ -1409,7 +1222,7 @@ }, { "cell_type": "markdown", - "id": "496cd78f", + "id": "ddc4f27e7412a024", "metadata": {}, "source": [ "## Routing and application" @@ -1418,7 +1231,7 @@ { "cell_type": "code", "execution_count": null, - "id": "03f4c639", + "id": "1537735647b1227f", "metadata": {}, "outputs": [], "source": [ @@ -1431,7 +1244,7 @@ { "cell_type": "code", "execution_count": null, - "id": "bdb2ac14", + "id": "3004b7d11797405c", "metadata": {}, "outputs": [], "source": [ @@ -1445,7 +1258,7 @@ { "cell_type": "code", "execution_count": null, - "id": "b80ce139", + "id": "e9de9e161764947b", "metadata": {}, "outputs": [], "source": [ @@ -1456,7 +1269,7 @@ { "cell_type": "code", "execution_count": null, - "id": "a27adc1e", + "id": "b9bb3ffe99344740", "metadata": {}, "outputs": [], "source": [ @@ -1474,7 +1287,7 @@ { "cell_type": "code", "execution_count": null, - "id": "46614165", + "id": "cccf24a4868dd227", "metadata": {}, "outputs": [], "source": [ @@ -1488,7 +1301,7 @@ { "cell_type": "code", "execution_count": null, - "id": "c1707d59", + "id": "535fa019103e6f9d", "metadata": {}, "outputs": [], "source": [ @@ -1522,7 +1335,7 @@ { "cell_type": "code", "execution_count": null, - "id": "f1e3ed2d", + "id": "69d2044af9aa17d4", "metadata": {}, "outputs": [], "source": [ @@ -1533,7 +1346,7 @@ { "cell_type": "code", "execution_count": null, - "id": "a407dc0e", + "id": "fecf15a81dec5af7", "metadata": {}, "outputs": [], "source": [ @@ -1552,7 +1365,7 @@ { "cell_type": "code", "execution_count": null, - "id": "d36402e6", + "id": "f50bb04220c638a9", "metadata": {}, "outputs": [], "source": [ @@ -1565,7 +1378,7 @@ { "cell_type": "code", "execution_count": null, - "id": "7f49728d", + "id": "d7ae82dfa40eb3f2", "metadata": {}, "outputs": [], "source": [ @@ -1581,7 +1394,7 @@ }, { "cell_type": "markdown", - "id": "cfae0a56", + "id": "b588b0f6c2e18bc6", "metadata": {}, "source": [ "Render fragment if `HX-Request` header is _present_ and\n", @@ -1591,7 +1404,7 @@ { "cell_type": "code", "execution_count": null, - "id": "b2007479", + "id": "a3674bc161b39a23", "metadata": {}, "outputs": [], "source": [ @@ -1605,7 +1418,7 @@ { "cell_type": "code", "execution_count": null, - "id": "358badec", + "id": "3ee9a5fb4b7929a3", "metadata": {}, "outputs": [], "source": [ @@ -1630,7 +1443,7 @@ { "cell_type": "code", "execution_count": null, - "id": "da449a7b", + "id": "c69f2a6c99eeeb1e", "metadata": {}, "outputs": [], "source": [ @@ -1654,7 +1467,7 @@ { "cell_type": "code", "execution_count": null, - "id": "775fb66b", + "id": "3651675357475aa2", "metadata": {}, "outputs": [], "source": [ @@ -1667,7 +1480,7 @@ { "cell_type": "code", "execution_count": null, - "id": "968d9245", + "id": "74898954bcd20abe", "metadata": {}, "outputs": [], "source": [ @@ -1695,7 +1508,7 @@ { "cell_type": "code", "execution_count": null, - "id": "eac44461", + "id": "4b0745e3157bccbb", "metadata": {}, "outputs": [], "source": [ @@ -1711,7 +1524,7 @@ { "cell_type": "code", "execution_count": null, - "id": "1ba52822", + "id": "147cb69ae182351c", "metadata": {}, "outputs": [], "source": [ @@ -1725,7 +1538,7 @@ { "cell_type": "code", "execution_count": null, - "id": "b0d1cbbf", + "id": "f7f626a00aad8476", "metadata": {}, "outputs": [], "source": [ @@ -1752,7 +1565,7 @@ }, { "cell_type": "markdown", - "id": "3531273d", + "id": "197c9278e1f04125", "metadata": {}, "source": [ "The FastHTML `exts` param supports the following:" @@ -1761,17 +1574,9 @@ { "cell_type": "code", "execution_count": null, - "id": "deffbaaa", + "id": "a9248bc09da25c47", "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "morph head-support preload class-tools loading-states multi-swap path-deps remove-me debug ws ws4 chunked-transfer sse4 live multipart\n" - ] - } - ], + "outputs": [], "source": [ "print(' '.join(htmx_exts))" ] @@ -1779,7 +1584,7 @@ { "cell_type": "code", "execution_count": null, - "id": "60cb52ea", + "id": "59076ca3b38a5fba", "metadata": {}, "outputs": [], "source": [ @@ -1796,7 +1601,7 @@ { "cell_type": "code", "execution_count": null, - "id": "8bd78eeb", + "id": "3f9e66d883079f28", "metadata": {}, "outputs": [], "source": [ @@ -1814,7 +1619,7 @@ { "cell_type": "code", "execution_count": null, - "id": "042666e2", + "id": "7eb35d0263b7da5a", "metadata": {}, "outputs": [], "source": [ @@ -1827,7 +1632,7 @@ { "cell_type": "code", "execution_count": null, - "id": "d276fc71", + "id": "87cbf1149a207d27", "metadata": {}, "outputs": [], "source": [ @@ -1847,7 +1652,7 @@ { "cell_type": "code", "execution_count": null, - "id": "bc323fd4", + "id": "f772e4bd5cb60fe2", "metadata": {}, "outputs": [], "source": [ @@ -1866,7 +1671,7 @@ }, { "cell_type": "markdown", - "id": "e51e2dc3", + "id": "9e0a824ad9d735f4", "metadata": {}, "source": [ "`qp` adds query parameters to route path strings" @@ -1875,7 +1680,7 @@ { "cell_type": "code", "execution_count": null, - "id": "ff82dc78", + "id": "491e70657d582c45", "metadata": {}, "outputs": [], "source": [ @@ -1885,7 +1690,7 @@ { "cell_type": "code", "execution_count": null, - "id": "c0836a8f", + "id": "bc4d62260c1ac7a9", "metadata": {}, "outputs": [], "source": [ @@ -1895,7 +1700,7 @@ }, { "cell_type": "markdown", - "id": "4740272f", + "id": "388f78c32327ad5e", "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." @@ -1904,7 +1709,7 @@ { "cell_type": "code", "execution_count": null, - "id": "50ebb1ee", + "id": "b005f90f77d725ea", "metadata": {}, "outputs": [], "source": [ @@ -1916,7 +1721,7 @@ { "cell_type": "code", "execution_count": null, - "id": "f86690c4", + "id": "7617757c40c72efe", "metadata": {}, "outputs": [], "source": [ @@ -1925,7 +1730,7 @@ " \"Default headers for a FastHTML app\"\n", " hdrs = []\n", " if surreal: hdrs = [surrsrc,scopesrc] + hdrs\n", - " if htmx and htmx4: \n", + " if htmx and htmx4:\n", " # metaCharacter=\"-\" makes htmx4 use dashes instead of colons\n", " meta_cfg = Meta(name=\"htmx-config\", content=json.dumps({\"metaCharacter\": \"-\"}))\n", " hdrs = [meta_cfg, htmx4src,fhjsscr] + hdrs \n", @@ -1937,7 +1742,7 @@ { "cell_type": "code", "execution_count": null, - "id": "2c5285ae", + "id": "77869926479cdf46", "metadata": {}, "outputs": [], "source": [ @@ -1970,7 +1775,7 @@ { "cell_type": "code", "execution_count": null, - "id": "17ced9a3", + "id": "f127a504464b0eb5", "metadata": {}, "outputs": [], "source": [ @@ -2043,7 +1848,7 @@ { "cell_type": "code", "execution_count": null, - "id": "3327a1e9", + "id": "c186654600ae903f", "metadata": {}, "outputs": [], "source": [ @@ -2089,7 +1894,7 @@ }, { "cell_type": "markdown", - "id": "c7d4052c", + "id": "8bd8ad987e8e02ed", "metadata": {}, "source": [ "### Routes" @@ -2098,7 +1903,7 @@ { "cell_type": "code", "execution_count": null, - "id": "dce68049", + "id": "4d43cd70f3e6cd75", "metadata": {}, "outputs": [], "source": [ @@ -2124,17 +1929,9 @@ { "cell_type": "code", "execution_count": null, - "id": "b8823cfe", + "id": "b14a50661eb6c393", "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "all passed\n" - ] - } - ], + "outputs": [], "source": [ "app = FastHTML()\n", "app.router.routes = []\n", @@ -2152,17 +1949,9 @@ { "cell_type": "code", "execution_count": null, - "id": "3da46acd", + "id": "6401176b1ba7ca40", "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "all passed\n" - ] - } - ], + "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", @@ -2176,7 +1965,7 @@ { "cell_type": "code", "execution_count": null, - "id": "e0accf76", + "id": "d100258e169dbbc7", "metadata": {}, "outputs": [], "source": [ @@ -2195,7 +1984,7 @@ { "cell_type": "code", "execution_count": null, - "id": "246bd8d1", + "id": "d7af2cc5decee07", "metadata": {}, "outputs": [], "source": [ @@ -2206,7 +1995,7 @@ { "cell_type": "code", "execution_count": null, - "id": "26b147ba", + "id": "e025b784db90b0f0", "metadata": {}, "outputs": [], "source": [ @@ -2243,7 +2032,7 @@ { "cell_type": "code", "execution_count": null, - "id": "3818575c", + "id": "3213bbd6e68c6eca", "metadata": {}, "outputs": [], "source": [ @@ -2261,7 +2050,7 @@ { "cell_type": "code", "execution_count": null, - "id": "669e76eb", + "id": "b04007ab3b0564b7", "metadata": {}, "outputs": [], "source": [ @@ -2276,7 +2065,7 @@ { "cell_type": "code", "execution_count": null, - "id": "j6ete5u68fo", + "id": "f327ebcd11de3159", "metadata": {}, "outputs": [], "source": [ @@ -2290,7 +2079,7 @@ { "cell_type": "code", "execution_count": null, - "id": "919618c3", + "id": "73a6816c7fc2a48e", "metadata": {}, "outputs": [], "source": [ @@ -2312,7 +2101,7 @@ { "cell_type": "code", "execution_count": null, - "id": "d2ecc738", + "id": "106d9bbb8cb464d1", "metadata": {}, "outputs": [], "source": [ @@ -2325,7 +2114,7 @@ { "cell_type": "code", "execution_count": null, - "id": "c0f13ece", + "id": "587180d55e32852b", "metadata": {}, "outputs": [], "source": [ @@ -2337,20 +2126,9 @@ { "cell_type": "code", "execution_count": null, - "id": "b218f738", + "id": "91c5715a38fc35ed", "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "'f_g'" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], + "outputs": [], "source": [ "func = f()\n", "nested_name(func)" @@ -2359,7 +2137,7 @@ { "cell_type": "code", "execution_count": null, - "id": "daafe4fc", + "id": "bf1de7b1007ef27a", "metadata": {}, "outputs": [], "source": [ @@ -2379,7 +2157,7 @@ { "cell_type": "code", "execution_count": null, - "id": "3710e48b", + "id": "2c1c95dde3ab364b", "metadata": {}, "outputs": [], "source": [ @@ -2412,7 +2190,7 @@ { "cell_type": "code", "execution_count": null, - "id": "f5cb2c2b", + "id": "1c4c8d49e989e7c7", "metadata": {}, "outputs": [], "source": [ @@ -2430,20 +2208,9 @@ { "cell_type": "code", "execution_count": null, - "id": "e6ee3a86", + "id": "a8a5d347ea952b15", "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "'/foo?a=bar&b=1&b=2'" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], + "outputs": [], "source": [ "app = FastHTML()\n", "@app.get\n", @@ -2455,20 +2222,9 @@ { "cell_type": "code", "execution_count": null, - "id": "9b9f1f03", + "id": "5f4225afe09d32b2", "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "'/foo/bar?b=1&b=2'" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], + "outputs": [], "source": [ "@app.get('/foo/{a}')\n", "def foo(a:str, b:list[int]): ...\n", @@ -2478,7 +2234,7 @@ }, { "cell_type": "markdown", - "id": "4ab96dc2", + "id": "30bd204b9ae3eb48", "metadata": {}, "source": [ "### Utils" @@ -2487,7 +2243,7 @@ { "cell_type": "code", "execution_count": null, - "id": "35c35a96", + "id": "bb214bd0b004e83c", "metadata": {}, "outputs": [], "source": [ @@ -2502,7 +2258,7 @@ { "cell_type": "code", "execution_count": null, - "id": "3a348474", + "id": "306333c1e9460062", "metadata": {}, "outputs": [], "source": [ @@ -2535,7 +2291,7 @@ }, { "cell_type": "markdown", - "id": "428b0e9c", + "id": "b0c79bd2f818722b", "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." @@ -2544,7 +2300,7 @@ { "cell_type": "code", "execution_count": null, - "id": "91b08e9a", + "id": "30c5cb0a53a38c92", "metadata": {}, "outputs": [], "source": [ @@ -2558,7 +2314,7 @@ }, { "cell_type": "markdown", - "id": "1129768b", + "id": "868be1a219c3dc25", "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." @@ -2567,7 +2323,7 @@ { "cell_type": "code", "execution_count": null, - "id": "c5220a0e", + "id": "157c183cd8bd0475", "metadata": {}, "outputs": [], "source": [ @@ -2589,7 +2345,7 @@ }, { "cell_type": "markdown", - "id": "8c6a8cb8", + "id": "738c7a7a629c8769", "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." @@ -2598,7 +2354,7 @@ { "cell_type": "code", "execution_count": null, - "id": "c5721d76", + "id": "63f31cbcd3a2cb7e", "metadata": {}, "outputs": [], "source": [ @@ -2620,7 +2376,7 @@ { "cell_type": "code", "execution_count": null, - "id": "8121968a", + "id": "778e281e884f69a4", "metadata": {}, "outputs": [], "source": [ @@ -2641,20 +2397,9 @@ { "cell_type": "code", "execution_count": null, - "id": "b163c933", + "id": "43bffe7939784946", "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "'test'" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], + "outputs": [], "source": [ "app = FastHTML(routes=[Route('/', lambda _: Response('test'))])\n", "cli = Client(app)\n", @@ -2664,7 +2409,7 @@ }, { "cell_type": "markdown", - "id": "efc8e6db", + "id": "d9cee9e6977a4004", "metadata": {}, "source": [ "Note that you can also use Starlette's `TestClient` instead of FastHTML's `Client`. They should be largely interchangable." @@ -2672,7 +2417,7 @@ }, { "cell_type": "markdown", - "id": "2d2633dd", + "id": "b3c16a868b4815b", "metadata": {}, "source": [ "## FastHTML Tests" @@ -2681,7 +2426,7 @@ { "cell_type": "code", "execution_count": null, - "id": "9abc3781", + "id": "2e90c46ddaaf39a4", "metadata": {}, "outputs": [], "source": [ @@ -2691,7 +2436,7 @@ { "cell_type": "code", "execution_count": null, - "id": "645d8d95", + "id": "6d6166efda69fd05", "metadata": {}, "outputs": [], "source": [ @@ -2701,27 +2446,9 @@ { "cell_type": "code", "execution_count": null, - "id": "421262a8", + "id": "c5b442f6f5d56b15", "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" - } - ], + "outputs": [], "source": [ "app,cli,rt = get_cli(FastHTML(title=\"My Custom Title\"))\n", "@app.get\n", @@ -2738,17 +2465,9 @@ { "cell_type": "code", "execution_count": null, - "id": "8836b62c", + "id": "7e36f21c33ef4204", "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" - ] - } - ], + "outputs": [], "source": [ "@rt(host='test.foo')\n", "def foo(): return Div(\"Goodbye World\")\n", @@ -2762,20 +2481,9 @@ { "cell_type": "code", "execution_count": null, - "id": "377012de", + "id": "48891dbe78e2901e", "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "'/foo?param=value'" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], + "outputs": [], "source": [ "response = cli.get('/foo')\n", "assert 'My Custom Title' in response.text\n", @@ -2786,7 +2494,7 @@ { "cell_type": "code", "execution_count": null, - "id": "2ebd6270", + "id": "3861d6a6d2e1877d", "metadata": {}, "outputs": [], "source": [ @@ -2802,7 +2510,7 @@ { "cell_type": "code", "execution_count": null, - "id": "274653c2", + "id": "2c737e80962d632a", "metadata": {}, "outputs": [], "source": [ @@ -2814,7 +2522,7 @@ { "cell_type": "code", "execution_count": null, - "id": "b8a77cde", + "id": "c70488e0bcf9f502", "metadata": {}, "outputs": [], "source": [ @@ -2836,7 +2544,7 @@ { "cell_type": "code", "execution_count": null, - "id": "ac7b527d", + "id": "36c96619662118d7", "metadata": {}, "outputs": [], "source": [ @@ -2851,20 +2559,9 @@ { "cell_type": "code", "execution_count": null, - "id": "8a6ed879", + "id": "e1bc26d746c79810", "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "'Hi there'" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], + "outputs": [], "source": [ "@rt(\"/hi\")\n", "def get(): return 'Hi there'\n", @@ -2876,20 +2573,9 @@ { "cell_type": "code", "execution_count": null, - "id": "a8e723fc", + "id": "2357dbfe20b61390", "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "'Postal'" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], + "outputs": [], "source": [ "@rt(\"/hi\")\n", "def post(): return 'Postal'\n", @@ -2900,20 +2586,9 @@ { "cell_type": "code", "execution_count": null, - "id": "274666db", + "id": "c8f3da32e20a2d24", "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "'testserver'" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], + "outputs": [], "source": [ "@app.get(\"/hostie\")\n", "def show_host(req): return req.headers['host']\n", @@ -2924,17 +2599,9 @@ { "cell_type": "code", "execution_count": null, - "id": "72428702", + "id": "2c29857acc9e9818", "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Message text was: Hi! with session bar, from client: Address(host='testclient', port=50000)\n" - ] - } - ], + "outputs": [], "source": [ "@app.get(\"/setsess\")\n", "def set_sess(session):\n", @@ -2955,20 +2622,9 @@ { "cell_type": "code", "execution_count": null, - "id": "36292bf3", + "id": "84e9f14b0cbe4741", "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "'a yoyo'" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], + "outputs": [], "source": [ "@rt\n", "def yoyo(): return 'a yoyo'\n", @@ -2979,21 +2635,9 @@ { "cell_type": "code", "execution_count": null, - "id": "0d813cd0", + "id": "44909d86b4f628e1", "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "\n", - "\n", - "
Text.
\n", - "\n", - "\n" - ] - } - ], + "outputs": [], "source": [ "@app.get\n", "def autopost(): return Html(Div('Text.', hx_post=yoyo()))\n", @@ -3003,23 +2647,9 @@ { "cell_type": "code", "execution_count": null, - "id": "52dde0da", + "id": "8599023efac0d0ea", "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "\n", - "\n", - " \n", - "
Text.
\n", - " \n", - "\n", - "\n" - ] - } - ], + "outputs": [], "source": [ "@app.get\n", "def autopost2(): return Html(Body(Div('Text.', cls='px-2', hx_post=show_host.to(a='b'))))\n", @@ -3029,21 +2659,9 @@ { "cell_type": "code", "execution_count": null, - "id": "d84d98f1", + "id": "439b66d0144f8ed1", "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "\n", - "\n", - "
Text.
\n", - "\n", - "\n" - ] - } - ], + "outputs": [], "source": [ "@app.get\n", "def autoget2(): return Html(Div('Text.', hx_get=show_host))\n", @@ -3053,20 +2671,9 @@ { "cell_type": "code", "execution_count": null, - "id": "64343367", + "id": "20571bea2a9a66d", "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "'Good day to you, Alexis!'" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], + "outputs": [], "source": [ "@rt('/user/{nm}', name='gday')\n", "def get(nm:str=''): return f\"Good day to you, {nm}!\"\n", @@ -3076,21 +2683,9 @@ { "cell_type": "code", "execution_count": null, - "id": "29a96715", + "id": "69a9fd107705ed47", "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "\n", - "\n", - "
Text.
\n", - "\n", - "\n" - ] - } - ], + "outputs": [], "source": [ "@app.get\n", "def autolink(): return Html(Div('Text.', link=uri('gday', nm='Alexis')))\n", @@ -3100,20 +2695,9 @@ { "cell_type": "code", "execution_count": null, - "id": "54266599", + "id": "41d305a1aa78fb54", "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "'http://testserver/user/Alexis; http://testserver/hostie'" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], + "outputs": [], "source": [ "@rt('/link')\n", "def get(req): return f\"{req.url_for('gday', nm='Alexis')}; {req.url_for('show_host')}\"\n", @@ -3124,17 +2708,9 @@ { "cell_type": "code", "execution_count": null, - "id": "162b811e", + "id": "8bb661471cb2ca13", "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Background task completed!\n" - ] - } - ], + "outputs": [], "source": [ "@app.get(\"/background\")\n", "async def background_task(request):\n", @@ -3149,7 +2725,7 @@ { "cell_type": "code", "execution_count": null, - "id": "db0281cf", + "id": "38c44ff35db35b25", "metadata": {}, "outputs": [], "source": [ @@ -3159,7 +2735,7 @@ { "cell_type": "code", "execution_count": null, - "id": "b827960a", + "id": "c574a6639678d314", "metadata": {}, "outputs": [], "source": [ @@ -3189,7 +2765,7 @@ { "cell_type": "code", "execution_count": null, - "id": "1c2311f8", + "id": "27219506256e3698", "metadata": {}, "outputs": [], "source": [ @@ -3203,7 +2779,7 @@ { "cell_type": "code", "execution_count": null, - "id": "381a1b68", + "id": "18a82ab866caacc0", "metadata": {}, "outputs": [], "source": [ @@ -3215,7 +2791,7 @@ { "cell_type": "code", "execution_count": null, - "id": "80238019", + "id": "46d13c3989713a0", "metadata": {}, "outputs": [], "source": [ @@ -3226,7 +2802,7 @@ { "cell_type": "code", "execution_count": null, - "id": "1b4b5717", + "id": "68b9a9c53831c6e4", "metadata": {}, "outputs": [], "source": [ @@ -3237,7 +2813,7 @@ { "cell_type": "code", "execution_count": null, - "id": "dd017867", + "id": "8088e5034676f071", "metadata": {}, "outputs": [], "source": [ @@ -3263,7 +2839,7 @@ { "cell_type": "code", "execution_count": null, - "id": "52d9a3f2", + "id": "a00df0aa1ccce1d1", "metadata": {}, "outputs": [], "source": [ @@ -3284,20 +2860,9 @@ { "cell_type": "code", "execution_count": null, - "id": "bb8154cc", + "id": "cf476961f5b1d0c6", "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "'got sub/a.b'" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], + "outputs": [], "source": [ "app = FastHTML()\n", "rt = app.route\n", @@ -3312,20 +2877,9 @@ { "cell_type": "code", "execution_count": null, - "id": "65a29643", + "id": "4bbc51e39895b2c2", "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "'also got sub/a.b,1'" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], + "outputs": [], "source": [ "cli.get('/static/sub/a.b?a=1').text" ] @@ -3333,7 +2887,7 @@ { "cell_type": "code", "execution_count": null, - "id": "6bc9564c", + "id": "c1c7645739c9eecb", "metadata": {}, "outputs": [], "source": [ @@ -3343,7 +2897,7 @@ { "cell_type": "code", "execution_count": null, - "id": "b8be4ef3", + "id": "48114b31ea9e71b0", "metadata": {}, "outputs": [], "source": [ @@ -3381,7 +2935,7 @@ { "cell_type": "code", "execution_count": null, - "id": "5f045cf9", + "id": "8cdcda801e94956f", "metadata": {}, "outputs": [], "source": [ @@ -3403,7 +2957,7 @@ { "cell_type": "code", "execution_count": null, - "id": "52f9f934", + "id": "ec6a3836a419e25d", "metadata": {}, "outputs": [], "source": [ @@ -3415,7 +2969,7 @@ { "cell_type": "code", "execution_count": null, - "id": "26d316b6", + "id": "a553403903b5cae9", "metadata": {}, "outputs": [], "source": [ @@ -3426,7 +2980,7 @@ { "cell_type": "code", "execution_count": null, - "id": "704aeba6", + "id": "459c74dfd6a88eae", "metadata": {}, "outputs": [], "source": [ @@ -3437,7 +2991,7 @@ { "cell_type": "code", "execution_count": null, - "id": "5fa127d5", + "id": "a7b198137f231c07", "metadata": {}, "outputs": [], "source": [ @@ -3448,7 +3002,7 @@ { "cell_type": "code", "execution_count": null, - "id": "356db6c0", + "id": "da0c027a530c6148", "metadata": {}, "outputs": [], "source": [ @@ -3463,7 +3017,7 @@ { "cell_type": "code", "execution_count": null, - "id": "a3596991", + "id": "e0a7ba54b5c713b3", "metadata": {}, "outputs": [], "source": [ @@ -3479,7 +3033,7 @@ { "cell_type": "code", "execution_count": null, - "id": "fdb9239c", + "id": "76c7ef29cdc149f3", "metadata": {}, "outputs": [], "source": [ @@ -3494,7 +3048,7 @@ { "cell_type": "code", "execution_count": null, - "id": "3366d88f", + "id": "8dec36d87f059d9", "metadata": {}, "outputs": [], "source": [ @@ -3534,7 +3088,7 @@ { "cell_type": "code", "execution_count": null, - "id": "fcc024e6", + "id": "ba61989e303abd08", "metadata": {}, "outputs": [], "source": [ @@ -3544,7 +3098,7 @@ { "cell_type": "code", "execution_count": null, - "id": "48f0a45e", + "id": "a22f4b8c32b4039b", "metadata": {}, "outputs": [], "source": [ @@ -3562,7 +3116,7 @@ { "cell_type": "code", "execution_count": null, - "id": "73363a37", + "id": "1be0bc9b1a258b7c", "metadata": {}, "outputs": [], "source": [ @@ -3578,7 +3132,7 @@ { "cell_type": "code", "execution_count": null, - "id": "0aeaac36", + "id": "93da225917fd0ebb", "metadata": {}, "outputs": [], "source": [ @@ -3593,7 +3147,7 @@ { "cell_type": "code", "execution_count": null, - "id": "4034ee37", + "id": "718c7f272bb77375", "metadata": {}, "outputs": [], "source": [ @@ -3603,18 +3157,9 @@ { "cell_type": "code", "execution_count": null, - "id": "04881594", + "id": "78f9c8b7cc4a6f8c", "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "200\n", - "content1,content2\n" - ] - } - ], + "outputs": [], "source": [ "@rt(\"/uploads\")\n", "async def post(files:list[UploadFile]): return ','.join([(await file.read()).decode() for file in files])\n", @@ -3627,7 +3172,7 @@ { "cell_type": "code", "execution_count": null, - "id": "28a99667", + "id": "33a842b973382258", "metadata": {}, "outputs": [], "source": [ @@ -3639,27 +3184,9 @@ { "cell_type": "code", "execution_count": null, - "id": "5bce33f0", + "id": "fa5e2a257fd14615", "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Set to 2026-10-30 12:59:28.473222\n" - ] - }, - { - "data": { - "text/plain": [ - "'Session time: 2026-10-30 12:59:28.473222'" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], + "outputs": [], "source": [ "@rt(\"/setsess\")\n", "def get(sess, foo:str=''):\n", @@ -3679,7 +3206,7 @@ { "cell_type": "code", "execution_count": null, - "id": "249fce31", + "id": "94b63c69eeb88e7c", "metadata": {}, "outputs": [], "source": [ @@ -3699,17 +3226,9 @@ { "cell_type": "code", "execution_count": null, - "id": "4d17ab9c", + "id": "8843e1a22d29d1c3", "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "# Release notes\n" - ] - } - ], + "outputs": [], "source": [ "@rt(\"/upload\")\n", "async def post(uf:UploadFile): return (await uf.read()).decode()\n", @@ -3720,7 +3239,7 @@ { "cell_type": "code", "execution_count": null, - "id": "102c17ab", + "id": "2e01ecd509708676", "metadata": {}, "outputs": [], "source": [ @@ -3733,7 +3252,7 @@ { "cell_type": "code", "execution_count": null, - "id": "85bf2984", + "id": "53e38d76286b1b72", "metadata": {}, "outputs": [], "source": [ @@ -3744,7 +3263,7 @@ { "cell_type": "code", "execution_count": null, - "id": "e4fc13b0", + "id": "6dff912b083465bc", "metadata": {}, "outputs": [], "source": [ @@ -3754,7 +3273,7 @@ { "cell_type": "code", "execution_count": null, - "id": "1f11eab1", + "id": "7548a47348034cec", "metadata": {}, "outputs": [], "source": [ @@ -3776,7 +3295,7 @@ { "cell_type": "code", "execution_count": null, - "id": "063b7f43", + "id": "2668d26c9512ef1a", "metadata": {}, "outputs": [], "source": [ @@ -3792,7 +3311,7 @@ { "cell_type": "code", "execution_count": null, - "id": "efd6fc6c", + "id": "37d3e15bcaa8a6ab", "metadata": {}, "outputs": [], "source": [ @@ -3809,7 +3328,7 @@ { "cell_type": "code", "execution_count": null, - "id": "32520197", + "id": "693350f5bae20896", "metadata": {}, "outputs": [], "source": [ @@ -3825,7 +3344,7 @@ }, { "cell_type": "markdown", - "id": "967001f3", + "id": "7878e0f298745bb6", "metadata": {}, "source": [ "HTMX4 fragment requests receive toast partials. Full pages render the toast container. Set `htmx=False, htmx4=True` when supplying your own HTMX4 script." @@ -3834,7 +3353,7 @@ { "cell_type": "code", "execution_count": null, - "id": "09a5fb96", + "id": "ea6ae9168eea4edb", "metadata": {}, "outputs": [], "source": [ @@ -3844,7 +3363,7 @@ { "cell_type": "code", "execution_count": null, - "id": "c7500555", + "id": "43d640dd834f7754", "metadata": {}, "outputs": [], "source": [ @@ -3872,7 +3391,7 @@ }, { "cell_type": "markdown", - "id": "bd0e4c06", + "id": "9c6af8473dc6a8b8", "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)." @@ -3881,7 +3400,7 @@ { "cell_type": "code", "execution_count": null, - "id": "e2417e5f", + "id": "2989e8b0111f0290", "metadata": {}, "outputs": [], "source": [ @@ -3891,7 +3410,7 @@ { "cell_type": "code", "execution_count": null, - "id": "f95e80d7", + "id": "d8abe51f9a1245e8", "metadata": {}, "outputs": [], "source": [ @@ -3908,7 +3427,7 @@ { "cell_type": "code", "execution_count": null, - "id": "190ce9d0", + "id": "c14bcde18b9cc46f", "metadata": {}, "outputs": [], "source": [ @@ -3925,7 +3444,7 @@ }, { "cell_type": "markdown", - "id": "b9fdbdd8", + "id": "421320e5cdf4c386", "metadata": {}, "source": [ "A route-level `before` can set session data, short-circuit with a response, or raise to block access:" @@ -3934,7 +3453,7 @@ { "cell_type": "code", "execution_count": null, - "id": "f94ea388", + "id": "6cf4a83e49cb21c3", "metadata": {}, "outputs": [], "source": [ @@ -3955,7 +3474,7 @@ }, { "cell_type": "markdown", - "id": "35615416", + "id": "f30c0190cbffc76a", "metadata": {}, "source": [ "Multiple `before` functions run in order, each receiving the injected request params:" @@ -3964,7 +3483,7 @@ { "cell_type": "code", "execution_count": null, - "id": "6b751acb", + "id": "cc638c1ceed7c22c", "metadata": {}, "outputs": [], "source": [ @@ -3979,7 +3498,7 @@ }, { "cell_type": "markdown", - "id": "49cc8791", + "id": "dc63cc1b1dec83b4", "metadata": {}, "source": [ "A truthy return from any `before` becomes the response; remaining `before`s and the handler are skipped (return `None` to continue):" @@ -3988,7 +3507,7 @@ { "cell_type": "code", "execution_count": null, - "id": "83188ab0", + "id": "b50f946c90a44d89", "metadata": {}, "outputs": [], "source": [ @@ -4007,7 +3526,7 @@ }, { "cell_type": "markdown", - "id": "a43466d4", + "id": "886f133f3cba0558", "metadata": {}, "source": [ "`cancel_on_disconnect` handlers keep their normal parameters; the handler is cancelled if the client disconnects, or after `timeout` seconds if given:" @@ -4016,7 +3535,7 @@ { "cell_type": "code", "execution_count": null, - "id": "4457e14e", + "id": "f93de0e0b133064e", "metadata": {}, "outputs": [], "source": [ @@ -4032,7 +3551,7 @@ { "cell_type": "code", "execution_count": null, - "id": "59ed14fc", + "id": "3222d6012fd42a71", "metadata": {}, "outputs": [], "source": [ @@ -4047,7 +3566,7 @@ }, { "cell_type": "markdown", - "id": "c03768de", + "id": "1b8b45a215beaa5c", "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:" @@ -4056,7 +3575,7 @@ { "cell_type": "code", "execution_count": null, - "id": "8e78bea6", + "id": "21a57425bf9e4f06", "metadata": {}, "outputs": [], "source": [ @@ -4080,7 +3599,7 @@ }, { "cell_type": "markdown", - "id": "6a014add", + "id": "11c7c66cb5b6b423", "metadata": {}, "source": [ "## APIRouter" @@ -4089,7 +3608,7 @@ { "cell_type": "code", "execution_count": null, - "id": "d5223a9a", + "id": "f1c11644b46e01d1", "metadata": {}, "outputs": [], "source": [ @@ -4108,7 +3627,7 @@ { "cell_type": "code", "execution_count": null, - "id": "0f08cb5e", + "id": "890c6b36806499f6", "metadata": {}, "outputs": [], "source": [ @@ -4156,7 +3675,7 @@ { "cell_type": "code", "execution_count": null, - "id": "22e17ec8", + "id": "95d50b50f5d9166f", "metadata": {}, "outputs": [], "source": [ @@ -4166,7 +3685,7 @@ { "cell_type": "code", "execution_count": null, - "id": "61030ee4", + "id": "bc3c688f39cdbfbe", "metadata": {}, "outputs": [], "source": [ @@ -4196,7 +3715,7 @@ { "cell_type": "code", "execution_count": null, - "id": "cd413b0d", + "id": "65dc2189b63305d0", "metadata": {}, "outputs": [], "source": [ @@ -4207,7 +3726,7 @@ { "cell_type": "code", "execution_count": null, - "id": "8c265ff8", + "id": "4569eb2492d2b8f7", "metadata": {}, "outputs": [], "source": [ @@ -4225,7 +3744,7 @@ { "cell_type": "code", "execution_count": null, - "id": "8f7c5710", + "id": "4691737b6959d800", "metadata": {}, "outputs": [], "source": [ @@ -4246,7 +3765,7 @@ { "cell_type": "code", "execution_count": null, - "id": "1236de78", + "id": "91d34d8ce1941c02", "metadata": {}, "outputs": [], "source": [ @@ -4259,7 +3778,7 @@ { "cell_type": "code", "execution_count": null, - "id": "02a4e649", + "id": "dad9a562054f33b7", "metadata": {}, "outputs": [], "source": [ @@ -4269,7 +3788,7 @@ { "cell_type": "code", "execution_count": null, - "id": "151b9e3c", + "id": "cbe4d060eb0c8360", "metadata": {}, "outputs": [], "source": [ @@ -4297,7 +3816,7 @@ { "cell_type": "code", "execution_count": null, - "id": "77ce8548", + "id": "9cee8fcc80b25168", "metadata": {}, "outputs": [], "source": [ @@ -4308,7 +3827,7 @@ { "cell_type": "code", "execution_count": null, - "id": "f1fc8425", + "id": "360f421b7fa3be15", "metadata": {}, "outputs": [], "source": [ @@ -4325,7 +3844,7 @@ { "cell_type": "code", "execution_count": null, - "id": "f265860d", + "id": "812c7fe6bd514944", "metadata": {}, "outputs": [], "source": [ @@ -4344,7 +3863,7 @@ { "cell_type": "code", "execution_count": null, - "id": "e38d99cf", + "id": "bab842b20bf23833", "metadata": {}, "outputs": [], "source": [ @@ -4357,7 +3876,7 @@ { "cell_type": "code", "execution_count": null, - "id": "259a0f53", + "id": "c01860fe7517722d", "metadata": {}, "outputs": [], "source": [ @@ -4368,7 +3887,7 @@ { "cell_type": "code", "execution_count": null, - "id": "f61d110c", + "id": "5528056ce46c6a8a", "metadata": {}, "outputs": [], "source": [ @@ -4389,7 +3908,7 @@ }, { "cell_type": "markdown", - "id": "dfa6f859", + "id": "e64ba1044537a083", "metadata": {}, "source": [ "## Extras" @@ -4398,7 +3917,7 @@ { "cell_type": "code", "execution_count": null, - "id": "7438435e", + "id": "f33d93dc0f7479a9", "metadata": {}, "outputs": [], "source": [ @@ -4408,7 +3927,7 @@ { "cell_type": "code", "execution_count": null, - "id": "e518de83", + "id": "6d41906f21e2e5bb", "metadata": {}, "outputs": [], "source": [ @@ -4433,37 +3952,9 @@ { "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", - "\n" - ] - }, - { - "data": { - "text/plain": [ - "'Cookie was set at time 12:59:28.565407'" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], + "id": "783b658eb1e826d6", + "metadata": {}, + "outputs": [], "source": [ "@rt(\"/setcookie\")\n", "def get(req): return cookie('now', datetime.now())\n", @@ -4479,7 +3970,7 @@ { "cell_type": "code", "execution_count": null, - "id": "8816f277", + "id": "acfb97d2b978356", "metadata": {}, "outputs": [], "source": [ @@ -4493,7 +3984,7 @@ { "cell_type": "code", "execution_count": null, - "id": "e9535978", + "id": "b5aea8aaa5b024d2", "metadata": {}, "outputs": [], "source": [ @@ -4513,7 +4004,7 @@ { "cell_type": "code", "execution_count": null, - "id": "9a70842e", + "id": "864d550f5ede18f4", "metadata": {}, "outputs": [], "source": [ @@ -4528,7 +4019,7 @@ { "cell_type": "code", "execution_count": null, - "id": "8bb51383", + "id": "579601c30f1d5d5f", "metadata": {}, "outputs": [], "source": [ @@ -4539,7 +4030,7 @@ { "cell_type": "code", "execution_count": null, - "id": "b31de65a", + "id": "179c165cf2d70fa0", "metadata": {}, "outputs": [], "source": [ @@ -4554,7 +4045,7 @@ { "cell_type": "code", "execution_count": null, - "id": "d4ff5919", + "id": "2683163724620ca6", "metadata": {}, "outputs": [], "source": [ @@ -4565,7 +4056,7 @@ { "cell_type": "code", "execution_count": null, - "id": "f63b7a03", + "id": "df8649e9ff8a4862", "metadata": {}, "outputs": [], "source": [ @@ -4581,7 +4072,7 @@ { "cell_type": "code", "execution_count": null, - "id": "74801f94", + "id": "b4b419bffadedf7c", "metadata": {}, "outputs": [], "source": [ @@ -4596,7 +4087,7 @@ }, { "cell_type": "markdown", - "id": "1c0531b8", + "id": "d373c46bcab32b6e", "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." @@ -4605,7 +4096,7 @@ { "cell_type": "code", "execution_count": null, - "id": "27910e71", + "id": "d3da7872f46f03e7", "metadata": {}, "outputs": [], "source": [ @@ -4620,7 +4111,7 @@ { "cell_type": "code", "execution_count": null, - "id": "e38fd6c7", + "id": "f650d7d18b386925", "metadata": {}, "outputs": [], "source": [ @@ -4638,7 +4129,7 @@ }, { "cell_type": "markdown", - "id": "bc5b7561", + "id": "149b12cab8090a07", "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." @@ -4647,7 +4138,7 @@ { "cell_type": "code", "execution_count": null, - "id": "28e4a133", + "id": "10948c5179e59f52", "metadata": {}, "outputs": [], "source": [ @@ -4667,7 +4158,7 @@ { "cell_type": "code", "execution_count": null, - "id": "7189daf8", + "id": "e336fb23b6a4348", "metadata": {}, "outputs": [], "source": [ @@ -4679,7 +4170,7 @@ { "cell_type": "code", "execution_count": null, - "id": "7eed23b7", + "id": "fffed22d52dd5db8", "metadata": {}, "outputs": [], "source": [ @@ -4698,7 +4189,7 @@ { "cell_type": "code", "execution_count": null, - "id": "9e5a9e88", + "id": "2908db7385793cc5", "metadata": {}, "outputs": [], "source": [ @@ -4727,7 +4218,7 @@ }, { "cell_type": "markdown", - "id": "eba9a334", + "id": "4f02960dbf53baf3", "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." @@ -4735,7 +4226,7 @@ }, { "cell_type": "markdown", - "id": "163acb67", + "id": "6b5ba96c6d368a14", "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." @@ -4744,7 +4235,7 @@ { "cell_type": "code", "execution_count": null, - "id": "50a9abbd", + "id": "236e1df02b7ecc4d", "metadata": {}, "outputs": [], "source": [ @@ -4759,7 +4250,7 @@ }, { "cell_type": "markdown", - "id": "9aa0ac77", + "id": "bfd647315eff2dcc", "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!\"." @@ -4768,7 +4259,7 @@ { "cell_type": "code", "execution_count": null, - "id": "3a08f786", + "id": "63f14214f7566860", "metadata": {}, "outputs": [], "source": [ @@ -4779,7 +4270,7 @@ }, { "cell_type": "markdown", - "id": "5a172800", + "id": "176b7099bc8abccf", "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`." @@ -4788,7 +4279,7 @@ { "cell_type": "code", "execution_count": null, - "id": "0fcfbf16", + "id": "c12782a920534773", "metadata": {}, "outputs": [], "source": [ @@ -4800,7 +4291,7 @@ { "cell_type": "code", "execution_count": null, - "id": "1960d7ff", + "id": "7f46d6e01ce2773c", "metadata": {}, "outputs": [], "source": [ @@ -4816,7 +4307,7 @@ { "cell_type": "code", "execution_count": null, - "id": "83a20f93", + "id": "bd853c5a477ed976", "metadata": {}, "outputs": [], "source": [ @@ -4839,7 +4330,7 @@ { "cell_type": "code", "execution_count": null, - "id": "a9e66b7d", + "id": "ddc9f8c2a6ff15e", "metadata": {}, "outputs": [], "source": [ @@ -4858,7 +4349,7 @@ }, { "cell_type": "markdown", - "id": "94705ca7", + "id": "570cebd3f8d38359", "metadata": {}, "source": [ "Test on a single background task:" @@ -4867,18 +4358,9 @@ { "cell_type": "code", "execution_count": null, - "id": "8cf7433e", + "id": "9452506485f1ae1", "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Starting slow task\n", - "Finished slow task\n" - ] - } - ], + "outputs": [], "source": [ "def my_slow_task():\n", " print('Starting slow task') \n", @@ -4896,7 +4378,7 @@ }, { "cell_type": "markdown", - "id": "47c26feb", + "id": "18cebd579c203d68", "metadata": {}, "source": [ "Test multiple background tasks:" @@ -4905,7 +4387,7 @@ { "cell_type": "code", "execution_count": null, - "id": "76d25483", + "id": "3533bbb53fd781f2", "metadata": {}, "outputs": [], "source": [ @@ -4919,22 +4401,9 @@ { "cell_type": "code", "execution_count": null, - "id": "bd7cf045", + "id": "642d1d90595ca371", "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Sleeping for 0.0s\n", - "Slept for 0.0s\n", - "Sleeping for 0.001s\n", - "Slept for 0.001s\n", - "Sleeping for 0.002s\n", - "Slept for 0.002s\n" - ] - } - ], + "outputs": [], "source": [ "@rt\n", "def backgrounds():\n", @@ -4949,22 +4418,9 @@ { "cell_type": "code", "execution_count": null, - "id": "5310fea9", + "id": "c185af1365da4fcc", "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Sleeping for 0.0s\n", - "Slept for 0.0s\n", - "Sleeping for 0.001s\n", - "Slept for 0.001s\n", - "Sleeping for 0.002s\n", - "Slept for 0.002s\n" - ] - } - ], + "outputs": [], "source": [ "@rt\n", "def backgrounds2():\n", @@ -4978,32 +4434,9 @@ { "cell_type": "code", "execution_count": null, - "id": "348f9bbd", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Sleeping for 0.0s\n", - "Slept for 0.0s\n", - "Sleeping for 0.001s\n", - "Slept for 0.001s\n", - "Sleeping for 0.002s\n", - "Slept for 0.002s\n" - ] - }, - { - "data": { - "text/plain": [ - "{'status': 'done'}" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], + "id": "2e211cf2afdf45fa", + "metadata": {}, + "outputs": [], "source": [ "@rt\n", "def backgrounds3():\n", @@ -5018,7 +4451,7 @@ { "cell_type": "code", "execution_count": null, - "id": "9dc1025e", + "id": "78bc2834a3ea6cda", "metadata": {}, "outputs": [], "source": [ @@ -5033,7 +4466,7 @@ { "cell_type": "code", "execution_count": null, - "id": "5b67e014", + "id": "7c977335a4ba289b", "metadata": {}, "outputs": [], "source": [ @@ -5047,7 +4480,7 @@ { "cell_type": "code", "execution_count": null, - "id": "1f590f25", + "id": "1a6b71aa1ba2e789", "metadata": {}, "outputs": [], "source": [ @@ -5066,7 +4499,7 @@ }, { "cell_type": "markdown", - "id": "98cdeef1", + "id": "ac318c208c76d21a", "metadata": {}, "source": [ "`setup_ws` returns an async function that broadcasts FT elements to connected clients. Here a message handler broadcasts each incoming message. Clients can disconnect and reconnect:" @@ -5075,7 +4508,7 @@ { "cell_type": "code", "execution_count": null, - "id": "7c0ab080", + "id": "3ac0ed38bb773298", "metadata": {}, "outputs": [], "source": [ @@ -5092,7 +4525,7 @@ { "cell_type": "code", "execution_count": null, - "id": "a8a91edd", + "id": "699ee6943e1c8ac6", "metadata": {}, "outputs": [], "source": [ @@ -5110,7 +4543,7 @@ { "cell_type": "code", "execution_count": null, - "id": "e27908c0", + "id": "75158856bbe1f5bf", "metadata": {}, "outputs": [], "source": [ @@ -5130,7 +4563,7 @@ { "cell_type": "code", "execution_count": null, - "id": "c845f437", + "id": "bb041161d82c7ec8", "metadata": {}, "outputs": [], "source": [ @@ -5146,7 +4579,7 @@ { "cell_type": "code", "execution_count": null, - "id": "49260e9b", + "id": "8e3efceea8c5b4e9", "metadata": {}, "outputs": [], "source": [ @@ -5169,7 +4602,7 @@ { "cell_type": "code", "execution_count": null, - "id": "6830083b", + "id": "74649fa5b13819c0", "metadata": {}, "outputs": [], "source": [ @@ -5179,7 +4612,7 @@ }, { "cell_type": "markdown", - "id": "474e14b4", + "id": "be77893080870385", "metadata": {}, "source": [ "## Export -" @@ -5188,7 +4621,7 @@ { "cell_type": "code", "execution_count": null, - "id": "d211e8e2", + "id": "da45ad161ba35516", "metadata": {}, "outputs": [], "source": [ diff --git a/tests/test_alias.py b/tests/test_alias.py new file mode 100644 index 00000000..8fd4138b --- /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("userId")]): return f"q:{user_id}" + +@rt("/form", methods=["post"]) +def post(user_id: Annotated[str, Alias("userId")]): return f"f:{user_id}" + +@rt("/path/{itemId}") +def get(item_id: Annotated[int, Alias("itemId")]): return f"p:{item_id}" + +@rt("/header") +def get(x_api_key_hdr: Annotated[str, Alias("X-Api-Key")]): return f"h:{x_api_key_hdr}" + +@rt("/cookie") +def get(req, sid_cookie: Annotated[str, Alias("session-id")]): return f"c:{sid_cookie}" + +@rt("/int") +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("userId")]): return user_id + +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?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: userId' in r.text