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",
- "