最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

python - Processing a list of zero or more checkboxes in FastHTML - Stack Overflow

programmeradmin2浏览0评论

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 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?

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 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?

Share Improve this question asked yesterday PhrogzPhrogz 303k113 gold badges667 silver badges756 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 1

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.

发布评论

评论列表(0)

  1. 暂无评论