diff --git a/htpy/starlette.py b/htpy/starlette.py new file mode 100644 index 0000000..e448bd9 --- /dev/null +++ b/htpy/starlette.py @@ -0,0 +1,30 @@ +from __future__ import annotations + +import typing as t + +from starlette.responses import StreamingResponse + +from . import aiter_node + +if t.TYPE_CHECKING: + from starlette.background import BackgroundTask + + from . import Node + + +class HtpyResponse(StreamingResponse): + def __init__( + self, + content: Node, + status_code: int = 200, + headers: t.Mapping[str, str] | None = None, + media_type: str | None = "text/html", + background: BackgroundTask | None = None, + ): + super().__init__( + aiter_node(content), + status_code=status_code, + headers=headers, + media_type=media_type, + background=background, + ) diff --git a/tests/test_starlette.py b/tests/test_starlette.py index 6ca9a3b..ec39229 100644 --- a/tests/test_starlette.py +++ b/tests/test_starlette.py @@ -7,7 +7,8 @@ from starlette.routing import Route from starlette.testclient import TestClient -from htpy import h1 +from htpy import Element, h1, p +from htpy.starlette import HtpyResponse if t.TYPE_CHECKING: from starlette.requests import Request @@ -17,11 +18,25 @@ async def html_response(request: Request) -> HTMLResponse: return HTMLResponse(h1["Hello, HTMLResponse!"]) +async def stuff() -> Element: + return p["stuff"] + + +async def htpy_response(request: Request) -> HtpyResponse: + return HtpyResponse( + ( + h1["Hello, HtpyResponse!"], + stuff(), + ) + ) + + client = TestClient( Starlette( debug=True, routes=[ Route("/html-response", html_response), + Route("/htpy-response", htpy_response), ], ) ) @@ -29,4 +44,10 @@ async def html_response(request: Request) -> HTMLResponse: def test_html_response() -> None: response = client.get("/html-response") - assert response.content == b"

Hello, HTMLResponse!

" + assert response.text == "

Hello, HTMLResponse!

" + + +def test_htpy_response() -> None: + response = client.get("/htpy-response") + assert response.headers["content-type"] == "text/html; charset=utf-8" + assert response.text == "

Hello, HtpyResponse!

stuff

"