|
| 1 | +# Async rendering |
| 2 | + |
| 3 | +htpy fully supports rendering HTML asynchronously. Combined with a async framework such as [Starlette/FastAPI](starlette.md), the entire web request can be processed async and the HTML page can be sent to the client incrementally as soon as it is ready. |
| 4 | + |
| 5 | +# Async components |
| 6 | + |
| 7 | +In addition to regular, [synchronous components](common-patterns.md), components can be defined as an `async def` coroutine. When rendering, htpy will `await` all async components: |
| 8 | + |
| 9 | +```py |
| 10 | +from htpy import li |
| 11 | +import asyncio |
| 12 | + |
| 13 | +async def get_text() -> str: |
| 14 | + return "hi!" |
| 15 | + |
| 16 | +async def my_text() -> Renderable: |
| 17 | + results = await get_text() |
| 18 | + return p[results] |
| 19 | +``` |
| 20 | + |
| 21 | +## Async iterators |
| 22 | + |
| 23 | +htpy will consume async iterators: |
| 24 | + |
| 25 | +```py |
| 26 | +from htpy import ul, li |
| 27 | + |
| 28 | +async def my_items() -> AsyncIterator[Renderable]: |
| 29 | + yield li["a"] |
| 30 | + yield li["b"] |
| 31 | + |
| 32 | +def my_list() -> Renderable: |
| 33 | + return ul[my_items()] |
| 34 | +``` |
| 35 | + |
| 36 | +# Rendering async content |
| 37 | + |
| 38 | +To retrieve results from async rendering, use the `aiter_chunks()` method. It returns an async iterator that yields the HTML document as bytes. |
| 39 | + |
| 40 | +```py |
| 41 | +import asyncio |
| 42 | + |
| 43 | +from htpy import p |
| 44 | + |
| 45 | +my_paragraph = p["hello!"] |
| 46 | + |
| 47 | + |
| 48 | +async def main() -> None: |
| 49 | + async for chunk in my_paragraph.aiter_chunks(): |
| 50 | + print(chunk) |
| 51 | + |
| 52 | + |
| 53 | +asyncio.run(main()) |
| 54 | + |
| 55 | +# output: |
| 56 | +# <p> |
| 57 | +# hello! |
| 58 | +# </p> |
| 59 | +``` |
| 60 | + |
| 61 | +The async iterator returned by `aiter_chunks()` can be passed to your web framework's streaming response class. See the [htpy Starlette docs](starlette.md) for more information how to integrate with Starlette. |
| 62 | + |
| 63 | +!!! warning |
| 64 | + |
| 65 | + Trying to get the string value of an async renderable like `str(element)` will result an exception: |
| 66 | + |
| 67 | + ```py |
| 68 | + Traceback (most recent call last): |
| 69 | + |
| 70 | + File "/Users/andreas/code/htpy/examples/async_in_sync_context.py", line 7, in <module> |
| 71 | + str(div[my_async_component()]) |
| 72 | + ~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 73 | + |
| 74 | + TypeError: <coroutine object my_async_component at 0x103471010> is not a valid child element. |
| 75 | + Use the `.aiter_chunks()` method to retrieve the content: https://htpy.dev/async/ |
| 76 | + ``` |
| 77 | + |
| 78 | + Instead, use `aiter_chunks()`: |
| 79 | + |
| 80 | + ```py |
| 81 | + async for chunk in div[my_async_component()].aiter_chunks(): |
| 82 | + print(chunk) |
| 83 | + ``` |
0 commit comments