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:
- HTMX makes a request for
/files?my_files=foo.txt&my_files=bar.txt
- FastHTML looks at the method signature and ~magically converts this into a list of
pathlib.Path
instances for me and exposes as the local variablemy_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?
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:
- HTMX makes a request for
/files?my_files=foo.txt&my_files=bar.txt
- FastHTML looks at the method signature and ~magically converts this into a list of
pathlib.Path
instances for me and exposes as the local variablemy_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?
Share Improve this question asked yesterday PhrogzPhrogz 303k113 gold badges667 silver badges756 bronze badges1 Answer
Reset to default 1The 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.