Skip to content

Commit

Permalink
Starlette HtpyResponse class
Browse files Browse the repository at this point in the history
  • Loading branch information
pelme committed Sep 15, 2024
1 parent 8970b1a commit 0fd9548
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 2 deletions.
30 changes: 30 additions & 0 deletions htpy/starlette.py
Original file line number Diff line number Diff line change
@@ -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,
)
25 changes: 23 additions & 2 deletions tests/test_starlette.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -17,16 +18,36 @@ 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),
],
)
)


def test_html_response() -> None:
response = client.get("/html-response")
assert response.content == b"<h1>Hello, HTMLResponse!</h1>"
assert response.text == "<h1>Hello, HTMLResponse!</h1>"


def test_htpy_response() -> None:
response = client.get("/htpy-response")
assert response.headers["content-type"] == "text/html; charset=utf-8"
assert response.text == "<h1>Hello, HtpyResponse!</h1><p>stuff</p>"

0 comments on commit 0fd9548

Please sign in to comment.