Module

middleware.streaming_html

Inject HTML snippets into streamedtext/html bodies before </body>.

BufferedResponse bodies are handled by HTMLInject. Streaming StreamingResponse chunks need a bounded buffer so </body>split across chunks is detected without materializing the entire body.

Functions

_chunks_to_async 1 AsyncIterator[str]
Normalize sync or async chunk iterators to async iteration.
async
async def _chunks_to_async(chunks: Iterator[str] | AsyncIterator[str]) -> AsyncIterator[str]
Parameters
Name Type Description
chunks Iterator[str] | AsyncIterator[str]
Returns
AsyncIterator[str]
async_stream_inject_before_body 5 AsyncIterator[str]
Yield HTML chunks, inserting *snippet* before the first *before* delimiter. If…
async
async def async_stream_inject_before_body(chunks: Iterator[str] | AsyncIterator[str], *, snippet: str, before: str = '</body>', dedup_marker: str | None = None, full_page_only: bool = True) -> AsyncIterator[str]

Yield HTML chunks, inserting snippet before the first before delimiter.

If dedup_marker is set and appears before the first before, the stream is passed through unchanged (no double injection).

If before never appears and full_page_only is True, the buffered tail is yielded as-is (same asHTMLInject when </body>is absent).

Handles before split across chunk boundaries via a bounded buffer.

Parameters
Name Type Description
chunks Iterator[str] | AsyncIterator[str]
snippet str
before str Default:'</body>'
dedup_marker str | None Default:None
full_page_only bool Default:True
Returns
AsyncIterator[str]