Skip to content

Commit

Permalink
starlette example
Browse files Browse the repository at this point in the history
  • Loading branch information
pelme committed Aug 10, 2024
1 parent 93f0dca commit 030451c
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 2 deletions.
39 changes: 39 additions & 0 deletions examples/starlette_app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import asyncio
from collections.abc import AsyncIterator

from starlette.applications import Starlette
from starlette.requests import Request
from starlette.responses import HTMLResponse, StreamingResponse

import htpy as h

app = Starlette(debug=True)


@app.route("/")
async def homepage(request: Request) -> HTMLResponse:
return HTMLResponse(
h.div[
h.h1["Hello, World!"],
h.p["This is a simple example of using htpy with Starlette."],
h.a(href=str(request.url_for("stream")))["Go to the async stream example"],
],
)


async def slow_numbers(minimum: int, maximum: int) -> AsyncIterator[int]:
for number in range(minimum, maximum + 1):
yield number
await asyncio.sleep(0.5)


@app.route("/stream", name="stream")
async def async_stream(request: Request) -> StreamingResponse:
return StreamingResponse(
h.div[
h.h1["Async Stream"],
h.p["This page is generated asyncronously."],
h.ul[(h.li[str(num)] async for num in slow_numbers(1, 10))],
],
media_type="text/html",
)
9 changes: 7 additions & 2 deletions htpy/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -139,11 +139,16 @@ def iter_node(x: Node) -> Iterator[str]:


async def aiter_node(x: Node) -> AsyncIterator[str]:
while isinstance(x, Awaitable) or (not isinstance(x, BaseElement) and callable(x)):
while True:
if isinstance(x, Awaitable):
x = await x
else:
continue

if not isinstance(x, BaseElement) and callable(x):
x = x()
continue

break

if x is None:
return
Expand Down

0 comments on commit 030451c

Please sign in to comment.