Async, 用于超媒体应用程序的纯 Python 服务器端渲染引擎。
Source code: https://github.com/volfpeter/htmy
Documentation and examples: https://volfpeter.github.io/htmy
htmyAsync, pure-Python server-side rendering engine.
Unleash your creativity with the full power and Python, without the hassle of learning a new templating language or dealing with its limitations!
ErrorBoundary component for graceful error handling.AnyIO."Thank you for your work on fasthx, as well as htmy! I've never had an easier time developing with another stack." (ref)
"One of the main parts of the FastAPI -> fasthx -> htmy integration I'm falling in love with is its explicitness, and not too much magic happening." (ref)
"Thank you for your work on htmy and fasthx, both have been very pleasant to use, and the APIs are both intuitive and simple. Great work." (ref)
"I love that the language-embedded HTML generation library approach is becoming more popular." (ref)
"Neat approach and it naturally solves the partial templates problem " (ref)
"Great API design!" (ref)
The package is available on PyPI and can be installed with:
$ pip install htmyThe package has the following optional dependency groups:
lxml (includes the lxml library, recommended): When installed, it is prioritized over xml.etree.ElementTree and provides more secure, faster, and more flexible HTML and XML processing. It is used, for example, for Markdown processing. Install with: pip install "htmy[lxml]".jinja (includes jinja2 and markupsafe): When installed, it provides support for rendering Jinja templates using the htmy.jinja module. Install with: pip install "htmy[jinja]".rs (includes htmy-rs): Optional native accelerator, providing 4-10x performance improvement, depending on the types of components in the rendered component tree. When installed, tag objects and the default renderer are transparently replaced by the corresponding Rust implementations without affecting user code. htmy.renderer.default:Renderer remains untouched, all other import paths are replaced. Rendering results are identical and htmy works the same without it. Install with: pip install "htmy[rs]".all: Installs all optional dependencies. Install with: pip install "htmy[all]".Consider supporting the development and maintenance of the project through sponsoring, or reach out for consulting so you can get the most out of the library.
The entire library -- from the rendering engine itself to the built-in components -- is built around a few simple protocols and a handful of simple utility classes. This means that you can easily customize, extend, or replace basically everything in the library. Yes, even the rendering engine. The remaining parts will keep working as expected.
Also, the library doesn't rely on advanced Python features such as metaclasses or descriptors. There are also no complex base classes and the like. Even a junior engineer could understand, develop, and debug an application that's built with htmy.
Every object with a sync or async htmy(context: Context) -> Component method is an htmy component (technically an HTMYComponentType). Strings are also components, as well as lists or tuples of HTMYComponentType or string objects. In many cases though, you don't even need to create components, simple functions that return components will be sufficient -- you can find out more about this in the Components guide of the documentation.
Using the htmy() method name enables the conversion of any of your pre-existing business objects (from TypedDictss or pydantic models to ORM classes) into components without the fear of name collision or compatibility issues with other tools.
Async support makes it possible to load data or execute async business logic right in your components. This can reduce the amount of boilerplate you need to write in some cases, and also gives you the freedom to split the rendering and non-rendering logic in any way you see fit.
Example:
…htmy also provides a powerful @component decorator that can be used on sync or async my_component(props: MyProps, context: Context) -> Component functions and methods to convert them into components (preserving the props typing). You can find out more about this feature in the Function components guide.
Here is the same example as above, but with function components:
…htmy has a rich set of built-in utilities and components for both HTML and other use-cases:
html module: a complete set of baseline HTML tags.Snippet and Slots: utilities for creating dynamic, customizable document snippets in their native file format (HTML, XML, Markdown, etc.), with slot rendering support.md: MarkdownParser utility and MD component for loading, parsing, converting, and rendering markdown content.i18n: utilities for async, JSON based internationalization.Tag, TagWithProps, and wildcard_tag: base classes and utilities for creating custom XML tags.ErrorBoundary, Fragment, SafeStr, WithContext: utilities for error handling, component wrappers, context providers, and formatting.etree.ETreeConverter: utility that converts XML to a component tree with support for custom HTMY components.htmy.Renderer is the built-in, default renderer of the library.
If you're using the library in an async web framework like FastAPI, then you're already in an async environment, so you can render components as simply as this: await Renderer().render(my_root_component).
If you're trying to run the renderer in a sync environment, like a local script or CLI, then you first need to wrap the renderer in an async task and execute that task with asyncio.run():
import asyncio
from htmy import Renderer, html
async def render_page() -> None:
page = (
html.DOCTYPE.html,
html.html(
html.body(
html.h1("Hello World!"),
html.p("This page was rendered by ", html.code("htmy")),
),
)
)
result = await Renderer().render(page)
print(result)
if __name__ == "__main__":
asyncio.run(render_page())As you could see from the code examples above, every component has a context: Context argument, which we haven't used so far. Context is a way to share data with the entire subtree of a component without "prop drilling".
The context (technically a Mapping) is entirely managed by the renderer. Context provider components (any class with a sync or async htmy_context() -> Context method) add new data to the context to make it available to components in their subtree (including themselves), and components can simply take what they need from the context.
There is no restriction on what can be in the context, it can be used for anything the application needs, for example making the current user, UI preferences, themes, or formatters available to components. In fact, built-in components get their Formatter from the context if it contains one, to make it possible to customize tag property name and value formatting.
Here's an example context provider and consumer implementation:
…You can of course rely on the built-in context related utilities like the ContextAware or WithContext classes for convenient and typed context use with less boilerplate code.
As mentioned before, the built-in Formatter class is responsible for tag attribute name and value formatting. You can completely override or extend the built-in formatting behavior simply by extending this class or adding new rules to an instance of it, and then adding the custom instance to the context, either directly in Renderer or Renderer.render(), or in a context provider component.
These are default tag attribute formatting rules:
_ -> -) unless the attribute name starts or ends with an underscore, in which case leading and trailing underscores are removed and the rest of attribute name is preserved. For example data_theme="dark" is converted to data-theme="dark", but _data_theme="dark" will end up as data_theme="dark" in the rendered text. More importantly class_="text-danger", _class="text-danger", _class__="text-danger" are all converted to class="text-danger", and _for="my-input" or for_="my_input" will become for="my-input".bool attribute values are converted to strings ("true" and "false").XBool.true attributes values are converted to an empty string, and XBool.false values are skipped (only the attribute name is rendered).date and datetime attribute values are converted to ISO strings.The ErrorBoundary component is useful if you want your application to fail gracefully (e.g. display an error message) instead of raising an HTTP error.
The error boundary wraps a component component subtree. When the renderer encounters an ErrorBoundary component, it will try to render its wrapped content. If rendering fails with an exception at any point in the ErrorBoundary's subtree, the renderer will automatically fall back to the component you assigned to the ErrorBoundary's fallback property.
Optionally, you can define which errors an error boundary can handle, giving you fine control over error handling.
In general, a component should be async if it must await some async call inside.
If a component executes a potentially "long-running" synchronous call, it is strongly recommended to delegate that call to a worker thread an await it (thus making the component async). This can be done for example with anyio's to_thread [utility](https://anyi
暂无开放 Issues,或尚未同步最近议题。