API reference¶
- class hyperscribe.DocWriter(writer: Writer[str] | Callable[[str], Ignored])[source]¶
Write escaped HTML fragments to a text stream or a function.
writeris anything with awrite(str)method, such as an open file or aio.StringIO, or a function that is called with each piece of text instead, such as theappendmethod of a list. Only thewritemethod is kept, so a writer that has one is never called itself.- tags: _TagBuilder¶
Tags by name, as in
doc.tags.div, ordoc.tags["my-element"].
- property parts: tuple[DocWriter, _TagBuilder, _Voids]¶
Return the writer, its tags and its void elements, for unpacking.
doc, t, v = DocWriter(output).partsgives short local names.
- __call__(value: TrustedContent) None[source]¶
Write trusted content verbatim, preserving the current indentation.
Strings with non-literal provenance must be passed to
escape(). Objects implementing__html__contribute their trusted HTML string; literal strings and primitive numeric values are also written verbatim. Tag content, as indoc.tags.p(...), is handled the same way.
- inline() AbstractContextManager[None][source]¶
Suppress line breaks and indentation for the markup written in the block.
The block is indented and ends its line like any other tag, so
with doc.inline(), doc.tags.div:renders the wholedivon one line. Blocks may be nested; formatting resumes once the outermost one exits.
- comment(text: str) None[source]¶
Write an HTML comment on its own line.
The text is written as given, so it must not be able to end the comment early. A
ValueErroris raised if it contains--.
- hyperscribe.Ignored¶
The return type of callbacks whose result hyperscribe does not look at.
It is
object, so functions returning anything at all are accepted, such aslist.append, which returnsNone, and a text stream’swrite, which returns the number of characters written. UnlikeAny, it does not switch off type checking of the result.
- hyperscribe.TrustedContent¶
Represent a union type
E.g. for int | str
- hyperscribe.AttributeValue¶
Represent a union type
E.g. for int | str
Markup¶
Helpers that turn values into text that is safe to write as HTML.
They are also available from hyperscribe itself.
- hyperscribe.markup.escape(value: str) SafeStr[source]¶
Escape
&,<,>and quotes so the text can be written as HTML.Quotes are escaped as well, so the result is safe in text and in attribute values.
- hyperscribe.markup.escape_silent(value: str | None) SafeStr[source]¶
Like
escape(), but writeNoneas an empty string.Use it for optional values, such as a field that may be missing in some data, where an empty result is what the page should show.
- hyperscribe.markup.trust(value: str) SafeStr[source]¶
Mark a string as safe to write as HTML, without escaping it.
Only use it for content that cannot contain untrusted input.
- hyperscribe.markup.tokenlist(*names: str | Mapping[str, object] | Literal[False] | None) SafeStr | None[source]¶
Join names into a space-separated list, such as the
classattribute.Each argument is a name, or several separated by spaces, or a mapping from names to whether to include them, so conditional names can be written next to fixed ones:
t.button("Save", class_=tokenlist("btn", {"active": is_active}, extra)) t.a("Docs", href=url, rel=tokenlist("noopener", {"noreferrer": external}))
It is named after the DOM’s
DOMTokenList, whichelement.classListandelement.relListare.NoneandFalseare skipped, sois_active and "active"works as an argument too. The names are escaped. If no names are left,Noneis returned, which leaves the attribute out altogether.
Streaming¶
Stream documents in chunks, for example to an async web server.
Templates still write synchronously to a DocWriter.
What they write is collected in a list,
and the document is sent on in chunks at the few places where it is worth it,
usually right before the template waits for something slow:
AsyncDocWritersends the buffer when the template callsawait doc.drain().aiter_chunks()turns a template written as an async generator into an async iterator of chunks, which most async web frameworks accept as a streaming response body. The document is split at each bareyield.iter_chunks()does the same for synchronous servers, such as WSGI ones, with a template written as a generator.
OutOfOrder works with the async ones.
It writes placeholders for slow content,
so the rest of the page can be sent first,
and fills them in as the content becomes available.
- class hyperscribe.streaming.AsyncDocWriter(send: Callable[[str], Awaitable[Ignored]])[source]¶
A writer that keeps what is written until
await doc.drain()sends it.Like
asyncio.StreamWriter.drain(),drain()waits until the data written so far has been passed on:sendis awaited with each chunk, so a slow client holds the template up instead of letting the buffer grow. It can be a wrapper around an ASGIsendcallable, or aroundasyncio.StreamWriter.write()anddrain(). Calldrain()once more when the template is done, to send whatever it wrote after the last time.The template sends the chunks itself, so timeouts and cancel scopes in it cover the sending as well, and can be used anywhere, unlike with
aiter_chunks().
- hyperscribe.streaming.aiter_chunks(template: ~collections.abc.Callable[[~typing.Concatenate[~hyperscribe.DocWriter, ~_P]], ~collections.abc.AsyncIterator[None]], /, *args: ~typing.~_P, **kwargs: ~typing.~_P) AsyncGenerator[str, None][source]¶
- hyperscribe.streaming.aiter_chunks(template: ~collections.abc.Callable[[~typing.Concatenate[~hyperscribe.DocWriter, ~_P]], ~collections.abc.Iterator[None]], /, *args: ~typing.~_P, **kwargs: ~typing.~_P) AsyncGenerator[str, None]
Render a generator template in chunks, as an async iterator of strings.
The template is called with a new
DocWriter, followed byargsandkwargs. It is an async generator, and the document is split each time it yields, so a bareyieldsends everything written up to that point. What it yields is ignored, and the rest of the document is sent when it returns. A synchronous generator is accepted as well, as foriter_chunks(), so the same template can be served by synchronous and async servers.Stopping the iterator early, as servers do when a client disconnects, closes the template, so its
finallyblocks andwithexits run.The template is paused at each
yieldwhile its chunk is sent, in the same task, as with any async generator. So it must not yield inside a block that limits its task, such asasyncio.timeout(), anasyncio.TaskGroupor a Trio cancel scope, which would otherwise limit sending the chunk as well. UseAsyncDocWriterfor templates that need such blocks around output.
- hyperscribe.streaming.iter_chunks(template: ~collections.abc.Callable[[~typing.Concatenate[~hyperscribe.DocWriter, ~_P]], ~collections.abc.Iterator[None]], /, *args: ~typing.~_P, **kwargs: ~typing.~_P) Generator[str, None, None][source]¶
Render a generator template in chunks, as an iterator of strings.
The template is called with a new
DocWriter, followed byargsandkwargs, and the document is split each time it yields, so a bareyieldsends everything written up to that point. What it yields is ignored, and the rest of the document is sent when it returns. This suits synchronous servers that accept an iterator as a response body, such as WSGI ones, which want the chunks encoded as bytes.Closing the iterator early closes the template, so its
finallyblocks andwithexits run.
- class hyperscribe.streaming.OutOfOrder(doc: DocWriter, *, prefix: str = 'hyperscribe-slot', nonce: str | None = None)[source]¶
Send the rest of the page while slow parts of it are still loading.
It is used in a
withstatement around the part of the page that contains the placeholders:with OutOfOrder(doc) as slots: t.div("Loading…", id=slots.defer(fetch_articles(), article_list)) t.footer("Thanks for reading") yield async for _ in slots.resolve(): yield
defer()starts waiting for the data of slow content in the background and returns the ID of a placeholder to write in its place.resolve()then renders each part as soon as its data arrives, in whatever order that is, inside a<template>followed by a small script that moves it into place in the browser. It yields after each part, so the template can send it on: with ayieldin an async generator template rendered byaiter_chunks(), or withawait doc.drain()for anAsyncDocWriter.If the block ends with an exception, including when the response is stopped because the client disconnected, the parts still loading are cancelled. If it ends without one while parts are still waiting to be resolved, they are cancelled as well and
RuntimeErroris raised.Waiting in the background uses
asynciotasks, so unlike the rest of this module it needs asyncio.- __init__(doc: DocWriter, *, prefix: str = 'hyperscribe-slot', nonce: str | None = None) None[source]¶
Write the placeholders and parts of
doc.Placeholders without an
idof their own get the IDsprefix-1,prefix-2and so on, soprefixhas to be unique within the page.nonceis added to each script, for pages with a content security policy that requires one.
- defer(awaitable: Awaitable[_T], render: Callable[[DocWriter, _T], None], /, *, id: str | None = None, keep: bool = False) SlotId[source]¶
Return the ID of a placeholder to write now, filled in by
renderlater.The placeholder is any element with this ID, written like any other, with a loading message for example:
t.div("Loading…", id=slots.defer(fetch_articles(), article_list)) with t.section(id=slots.defer(fetch_articles(), article_list)): t.h2("Articles") t.p("Loading…")
Once the data has arrived,
render(doc, data)is called, and by default the placeholder is replaced as a whole by what it writes. Withkeep, the element stays and only its content is replaced, so the element becomes the parent of whatrenderwrites.The ID is
idif given, which is then up to the caller to keep unique, and made from the prefix otherwise.awaitablestarts running right away, so several deferred parts load concurrently.
- write_completed() int[source]¶
Write the deferred parts whose data has already arrived, without waiting.
Call it before waiting for something slow that is not deferred, and send them on with a
yield, orawait doc.drain()for anAsyncDocWriter, so the parts that are done are sent first. Returns how many parts were written.
- async resolve() AsyncIterator[None][source]¶
Render the deferred parts in the order their data arrives.
This yields after writing each part, so the caller can send it on:
async for _ in slots.resolve(): yield # or: await doc.drain()
Call it inside the
withblock, where the parts should be written, usually right before</body>. Parts whose data arrives together are written in the order they were deferred. If rendering a part fails, the parts still loading are cancelled.
- cancel() None[source]¶
Stop waiting for the deferred parts that have not been written yet.
Their awaitables are cancelled, including tasks and futures that were passed to
defer()as they are.
- __exit__(exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None) None[source]¶
Cancel the parts that have not been written.
If the block ends without an exception while parts are left,
resolve()was not called for them, andRuntimeErroris raised.
- class hyperscribe.streaming.SlotId(target: str)[source]¶
The ID of a deferred part’s placeholder, from
OutOfOrder.defer().Write it as the
idof the element that the part should take the place of, as int.div("Loading…", id=slot). It is written escaped, and only once, so thatOutOfOrder.resolve()can tell whether every placeholder is in the page.
Tag objects¶
tags is a tag builder,
and voids looks up void element builders.
They are documented here because they appear in the signatures above,
but you normally do not create them yourself.
- class hyperscribe._TagBuilder(_doc: DocWriter, _openings: tuple[str, ...], _closings: tuple[str, ...], _children: dict[str, _TagBuilder] | None = None)[source]¶
Represent a chain of tags, usable directly or with attributes supplied by a call.
Builders are immutable, so they can be cached and nested inside themselves.
- __getattr__(name: str) _TagBuilder[source]¶
Return a builder for a nested tag, such as
mainindoc.body.main.
- __getitem__(name: str) _TagBuilder[source]¶
Return a builder for a nested tag, as in
doc.div["x-y"].
- __call__(**attrs: AttributeValue) _TagBuilder[source]¶
- __call__(content: TrustedContent, /, **attrs: AttributeValue) None
Write a leaf element when given content, else return a builder.
Attributes are added to the innermost tag, after any it was given by an earlier call. The content is handled like that of
DocWriter.__call__(): it is written verbatim, so a string that is not a literal has to go throughescape()first.Noneis rejected with aTypeErrorinstead of being mistaken for missing content.
- class hyperscribe._Voids(_doc: DocWriter, _builders: dict[str, ~hyperscribe._VoidBuilder]=<factory>)[source]¶
Look up void elements by name, as in
doc.voids.br().- __getattr__(name: str) _VoidBuilder[source]¶
Return the void element with this name, such as
img.
- __getitem__(name: str) _VoidBuilder[source]¶
Return the void element with any name, as in
doc.voids["x-y"].
- class hyperscribe._VoidBuilder(_doc: DocWriter, _opening: str)[source]¶
Write a void element, such as
<br>, on its own line when called.- __call__(**attrs: AttributeValue) None[source]¶
Write the element with the given attributes.
Void elements have no content and no closing tag, so there is nothing to pass as content or to enter as a context manager.