From d7a0bc67c5ff3fcb2c8f861d43e27bdd6e496537 Mon Sep 17 00:00:00 2001 From: Peter Volf Date: Mon, 9 Sep 2024 13:26:29 +0200 Subject: [PATCH] added the Jinja.no_data property + tests + version bump to rc3 --- fasthx/jinja.py | 10 +++++++++- pyproject.toml | 2 +- tests/test_jinja.py | 12 ++++++++++-- 3 files changed, 20 insertions(+), 4 deletions(-) diff --git a/fasthx/jinja.py b/fasthx/jinja.py index a9668ec..a70d5cd 100644 --- a/fasthx/jinja.py +++ b/fasthx/jinja.py @@ -273,6 +273,14 @@ class Jinja: a Jinja rendering context. The default value is `JinjaContext.unpack_result`. """ + no_data: bool = field(default=False, kw_only=True) + """ + If set, `hx()` routes will only accept HTMX requests. + + Note that if this property is `True`, then the `hx()` decorator's `no_data` argument + will have no effect. + """ + def hx( self, template: ComponentSelector[str], @@ -304,7 +312,7 @@ def hx( render_error=None if error_template is None else self._make_render_function(error_template, make_context=make_context, prefix=prefix), - no_data=no_data, + no_data=self.no_data or no_data, ) def page( diff --git a/pyproject.toml b/pyproject.toml index 66877af..6d4e1e4 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [tool.poetry] name = "fasthx" -version = "2.0.0-rc2" +version = "2.0.0-rc3" description = "FastAPI data APIs with HTMX support." authors = ["Peter Volf "] readme = "README.md" diff --git a/tests/test_jinja.py b/tests/test_jinja.py index aca8bbe..70b13d0 100644 --- a/tests/test_jinja.py +++ b/tests/test_jinja.py @@ -39,6 +39,7 @@ def jinja_app() -> FastAPI: app = FastAPI() jinja = Jinja(Jinja2Templates("tests/templates")) + no_data_jinja = Jinja(Jinja2Templates("tests/templates"), no_data=True) @app.get("/") @jinja.page("user-list.jinja") @@ -113,6 +114,11 @@ def error(response: Response) -> None: def error_page(response: Response) -> None: raise RenderedError({"a": 1, "b": 2}, response=response) + @app.get("/global-no-data") + @no_data_jinja.hx("user-list.jinja", no_data=False) + def global_no_data() -> list[User]: + return [] + return app @@ -186,10 +192,12 @@ def jinja_client(jinja_app: FastAPI) -> TestClient: ("/htmx-only", {"HX-Request": "true"}, 200, user_list_html, {}), ("/htmx-only", None, 400, "", {}), ("/htmx-only", {"HX-Request": "false"}, 400, "", {}), - # hx error rendering + # hx() error rendering ("/error", {"HX-Request": "true"}, 456, "Hello World!", {}), - # page error rendering + # page() error rendering ("/error-page", None, 456, "Hello World!", {}), + # Globally disabled data responses + ("/global-no-data", None, 400, "", {}), ), ) def test_jinja(