With FastHTML I'm writing a route to process a list of same-named checkboxes representing filenames in a Pico CSS Dropdown passed in a query string by HTMX:
@rt.get("/files")
def files_selected(my_files: list[pathlib.Path]):
print("\n".join(f.name for f in my_files))
This works nicely most of the time:
/files?my_files=foo.txt&my_files=bar.txt
pathlib.Path
instances for me and exposes as the local variable my_files
.However, when no checkboxes are passed—when HTXML requests just /files
with no query string—FastHTML throws HTTP 400 with the response Missing required field: my_files
.
I tried switching the function signature to…
def files_selected(my_files: list[pathlib.Path] | None = None):
…but that breaks the magic; passing a single file results in
my_files=['f', 'o', 'o', '.', 't', 'x', 't']
.
I've tried changing the function to…
def files_selected(req: fh.starlette.Request):
my_files = req.query_params["my_files"]
…but this only returns one file (as a string) when multiple are supplied.
What's the right way to accept optional parameters in the query string?
The answer is simple:
@rt.get("/files")
def files_selected(my_files: list[pathlib.Path] = []):
print("\n".join(f.name for f in my_files))
Provide a default value for the list.