From 23a0aee59f095bf19addd83fafe2b2e8516ba7a1 Mon Sep 17 00:00:00 2001 From: Andreas Pelme Date: Wed, 31 Jul 2024 21:14:53 +0200 Subject: [PATCH] Implement .encode() to allow Starlette Response to consume a htpy element directly. --- htpy/__init__.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/htpy/__init__.py b/htpy/__init__.py index 3a6749f..ceb8af2 100644 --- a/htpy/__init__.py +++ b/htpy/__init__.py @@ -273,6 +273,12 @@ def _iter_context(self, ctx: dict[Context[t.Any], t.Any]) -> Iterator[str]: def __repr__(self) -> str: return f"<{self.__class__.__name__} '{self}'>" + # Allow starlette Response.render to directly render this element without + # explicitly casting to str: + # https://github.com/encode/starlette/blob/5ed55c441126687106109a3f5e051176f88cd3e6/starlette/responses.py#L44-L49 + def encode(self, encoding: str = "utf-8", errors: str = "strict") -> bytes: + return str(self).encode(encoding, errors) + # Avoid having Django "call" a htpy element that is injected into a # template. Setting do_not_call_in_templates will prevent Django from doing # an extra call: