Skip to content

API Reference

holm.App(*, app=None, htmy=None)

Creates a FastAPI application with all the routes that are defined in the application package.

Parameters:

Name Type Description Default
app FastAPI | None

Optional FastAPI application to use. If None, a new instance will be created.

None
htmy HTMY | None

Optional fasthx.htmy.HTMY instance to use for server-side rendering. If None, a default instance will be created.

None
Source code in holm/app.py
def App(*, app: FastAPI | None = None, htmy: HTMY | None = None) -> FastAPI:
    """
    Creates a FastAPI application with all the routes that are defined in the application package.

    Arguments:
        app: Optional FastAPI application to use. If `None`, a new instance will be created.
        htmy: Optional `fasthx.htmy.HTMY` instance to use for server-side rendering. If `None`,
            a default instance will be created.
    """
    if app is None:
        app = FastAPI()

    if htmy is None:
        htmy = HTMY()

    config = AppConfig.default()
    packages = _discover_app_packages(config)
    root_node = _build_app_tree(packages)

    # Register error handlers
    if pkg := root_node.package:
        register_error_handlers(app, pkg.import_module("error", is_error_handler_owner), htmy=htmy)

    # Build the API
    app.include_router(_build_api(root_node, htmy=htmy))

    return app

holm.Metadata

Bases: ContextAware

Context-aware metadata provider.

The class implements the Mapping protocol as a means of giving convenient access to the metadata it contains.

Source code in holm/module_options/_metadata.py
class Metadata(ContextAware):
    """
    Context-aware metadata provider.

    The class implements the `Mapping` protocol as a means of giving convenient access to
    the metadata it contains.
    """

    __slots__ = ("_metadata",)

    def __init__(self, metadata: MetadataMapping | None = None) -> None:
        """
        Initialization.

        Arguments:
            metadata: The actual metadata mapping.
        """
        self._metadata = {} if metadata is None else metadata
        """The metadata mapping."""

    @overload
    def get(self, key: Any, default: None = None) -> Any | None: ...

    @overload
    def get(self, key: Any, default: Any) -> Any: ...

    def get(self, key: Any, default: Any | None = None) -> Any | None:
        """Implements `Mapping.get()`."""
        return self._metadata.get(key, default)

    def __contains__(self, key: Any) -> bool:
        """Implements the `Container` protocol."""
        return key in self._metadata

    def __eq__(self, other: Any) -> bool:
        return isinstance(other, Metadata) and self._metadata == other._metadata

    def __getitem__(self, key: Any) -> Any:
        """Implements the `Sequence` protocol."""
        return self._metadata[key]

    def __iter__(self) -> Iterator[Any]:
        """Implements the `Iterable` protocol."""
        return iter(self._metadata)

    def __len__(self) -> int:
        """Implements the `Sized` protocol."""
        return len(self._metadata)

    def __ne__(self, other: Any) -> bool:
        return not self.__eq__(other)

    def items(self) -> ItemsView[Any, Any]:
        """Implements `Mapping.items()`."""
        return self._metadata.items()

    def keys(self) -> KeysView[Any]:
        """Implements `Mapping.keys()`."""
        return self._metadata.keys()

    def values(self) -> ValuesView[Any]:
        """Implements `Mapping.values()`."""
        return self._metadata.values()

__contains__(key)

Implements the Container protocol.

Source code in holm/module_options/_metadata.py
def __contains__(self, key: Any) -> bool:
    """Implements the `Container` protocol."""
    return key in self._metadata

__getitem__(key)

Implements the Sequence protocol.

Source code in holm/module_options/_metadata.py
def __getitem__(self, key: Any) -> Any:
    """Implements the `Sequence` protocol."""
    return self._metadata[key]

__iter__()

Implements the Iterable protocol.

Source code in holm/module_options/_metadata.py
def __iter__(self) -> Iterator[Any]:
    """Implements the `Iterable` protocol."""
    return iter(self._metadata)

__len__()

Implements the Sized protocol.

Source code in holm/module_options/_metadata.py
def __len__(self) -> int:
    """Implements the `Sized` protocol."""
    return len(self._metadata)

get(key, default=None)

get(key: Any, default: None = None) -> Any | None
get(key: Any, default: Any) -> Any

Implements Mapping.get().

Source code in holm/module_options/_metadata.py
def get(self, key: Any, default: Any | None = None) -> Any | None:
    """Implements `Mapping.get()`."""
    return self._metadata.get(key, default)

items()

Implements Mapping.items().

Source code in holm/module_options/_metadata.py
def items(self) -> ItemsView[Any, Any]:
    """Implements `Mapping.items()`."""
    return self._metadata.items()

keys()

Implements Mapping.keys().

Source code in holm/module_options/_metadata.py
def keys(self) -> KeysView[Any]:
    """Implements `Mapping.keys()`."""
    return self._metadata.keys()

values()

Implements Mapping.values().

Source code in holm/module_options/_metadata.py
def values(self) -> ValuesView[Any]:
    """Implements `Mapping.values()`."""
    return self._metadata.values()

holm.action

Decorators for registering actions.

Decorator arguments map directly to the corresponding FastAPI route decorator's arguments, unless the documentation states otherwise.

Source code in holm/module_options/_actions.py
class action:
    """
    Decorators for registering actions.

    Decorator arguments map directly to the corresponding FastAPI route decorator's arguments,
    unless the documentation states otherwise.
    """

    @classmethod
    def __call__(
        cls,
        path: str | None = None,
        *,
        use_layout: bool = False,
        metadata: MetadataMappingOrDependency | None = None,
        methods: Collection[HTTPMethod] | None = None,
        dependencies: Sequence[DependsParam] | None = None,
        deprecated: bool | None = None,
        tags: list[str | Enum] | None = None,
    ) -> ActionDependencyDecorator:
        """
        Decorator for registering an action with arbitrary HTTP `methods`.

        Corresponding FastAPI route decorator: `APIRouter.api_route()`.

        Arguments:
            use_layout: Whether to render the action's return value in the
                containing package's layout (same as a page).
            metadata: Metadata mapping or dependency for the action. The equivalent
                of page metadata for actions.
            path: The action's path (within the package's `APIRouter`). If `None`,
                the decorated function's name is used as the path.
        """

        def decorator(func: ActionDependency) -> ActionDependency:
            cls._register_action(
                func,
                use_layout=use_layout,
                metadata=metadata,
                path=path,
                dependencies=dependencies,
                deprecated=deprecated,
                methods=methods,
                tags=tags,
            )
            return func

        return decorator

    @classmethod
    def get(
        cls,
        path: str | None = None,
        *,
        use_layout: bool = False,
        metadata: MetadataMappingOrDependency | None = None,
        dependencies: Sequence[DependsParam] | None = None,
        deprecated: bool | None = None,
        tags: list[str | Enum] | None = None,
    ) -> ActionDependencyDecorator:
        """
        Decorator for registering an action with an HTTP GET method.

        Corresponding FastAPI route decorator: `APIRouter.get()`.

        Arguments:
            use_layout: Whether to render the action's return value in the
                containing package's layout (same as a page).
            metadata: Metadata mapping or dependency for the action. The equivalent
                of page metadata for actions.
            path: The action's path (within the package's `APIRouter`). If `None`,
                the decorated function's name is used as the path.
        """

        def decorator(func: ActionDependency) -> ActionDependency:
            cls._register_action(
                func,
                use_layout=use_layout,
                metadata=metadata,
                path=path,
                dependencies=dependencies,
                deprecated=deprecated,
                methods=("GET",),
                tags=tags,
            )
            return func

        return decorator

    @classmethod
    def post(
        cls,
        path: str | None = None,
        *,
        use_layout: bool = False,
        metadata: MetadataMappingOrDependency | None = None,
        dependencies: Sequence[DependsParam] | None = None,
        deprecated: bool | None = None,
        tags: list[str | Enum] | None = None,
    ) -> ActionDependencyDecorator:
        """
        Decorator for registering an action with an HTTP POST method.

        Corresponding FastAPI route decorator: `APIRouter.post()`.

        Arguments:
            use_layout: Whether to render the action's return value in the
                containing package's layout (same as a page).
            metadata: Metadata mapping or dependency for the action. The equivalent
                of page metadata for actions.
            path: The action's path (within the package's `APIRouter`). If `None`,
                the decorated function's name is used as the path.
        """

        def decorator(func: ActionDependency) -> ActionDependency:
            cls._register_action(
                func,
                use_layout=use_layout,
                metadata=metadata,
                path=path,
                dependencies=dependencies,
                deprecated=deprecated,
                methods=("POST",),
                tags=tags,
            )
            return func

        return decorator

    @classmethod
    def put(
        cls,
        path: str | None = None,
        *,
        use_layout: bool = False,
        metadata: MetadataMappingOrDependency | None = None,
        dependencies: Sequence[DependsParam] | None = None,
        deprecated: bool | None = None,
        tags: list[str | Enum] | None = None,
    ) -> ActionDependencyDecorator:
        """
        Decorator for registering an action with an HTTP PUT method.

        Corresponding FastAPI route decorator: `APIRouter.put()`.

        Arguments:
            use_layout: Whether to render the action's return value in the
                containing package's layout (same as a page).
            metadata: Metadata mapping or dependency for the action. The equivalent
                of page metadata for actions.
            path: The action's path (within the package's `APIRouter`). If `None`,
                the decorated function's name is used as the path.
        """

        def decorator(func: ActionDependency) -> ActionDependency:
            cls._register_action(
                func,
                use_layout=use_layout,
                metadata=metadata,
                path=path,
                dependencies=dependencies,
                deprecated=deprecated,
                methods=("PUT",),
                tags=tags,
            )
            return func

        return decorator

    @classmethod
    def patch(
        cls,
        path: str | None = None,
        *,
        use_layout: bool = False,
        metadata: MetadataMappingOrDependency | None = None,
        dependencies: Sequence[DependsParam] | None = None,
        deprecated: bool | None = None,
        tags: list[str | Enum] | None = None,
    ) -> ActionDependencyDecorator:
        """
        Decorator for registering an action with an HTTP PATCH method.

        Corresponding FastAPI route decorator: `APIRouter.patch()`.

        Arguments:
            use_layout: Whether to render the action's return value in the
                containing package's layout (same as a page).
            metadata: Metadata mapping or dependency for the action. The equivalent
                of page metadata for actions.
            path: The action's path (within the package's `APIRouter`). If `None`,
                the decorated function's name is used as the path.
        """

        def decorator(func: ActionDependency) -> ActionDependency:
            cls._register_action(
                func,
                use_layout=use_layout,
                metadata=metadata,
                path=path,
                dependencies=dependencies,
                deprecated=deprecated,
                methods=("PATCH",),
                tags=tags,
            )
            return func

        return decorator

    @classmethod
    def delete(
        cls,
        path: str | None = None,
        *,
        use_layout: bool = False,
        metadata: MetadataMappingOrDependency | None = None,
        dependencies: Sequence[DependsParam] | None = None,
        deprecated: bool | None = None,
        tags: list[str | Enum] | None = None,
    ) -> ActionDependencyDecorator:
        """
        Decorator for registering an action with an HTTP DELETE method.

        Corresponding FastAPI route decorator: `APIRouter.delete()`.

        Arguments:
            use_layout: Whether to render the action's return value in the
                containing package's layout (same as a page).
            metadata: Metadata mapping or dependency for the action. The equivalent
                of page metadata for actions.
            path: The action's path (within the package's `APIRouter`). If `None`,
                the decorated function's name is used as the path.
        """

        def decorator(func: ActionDependency) -> ActionDependency:
            cls._register_action(
                func,
                use_layout=use_layout,
                metadata=metadata,
                path=path,
                dependencies=dependencies,
                deprecated=deprecated,
                methods=("DELETE",),
                tags=tags,
            )
            return func

        return decorator

    @classmethod
    def _register_action(
        cls,
        action: ActionDependency,
        *,
        use_layout: bool,
        metadata: MetadataMappingOrDependency | None,
        path: str | None,
        tags: list[str | Enum] | None,
        **route_args: Any,
    ) -> None:
        """
        Registers the given action in the module that contains it.

        Arguments:
            use_layout: Whether to render the action's return value in the
                containing package's layout (same as a page).
            metadata: Metadata mapping or dependency for the action. The equivalent
                of page metadata for actions.
            path: The action's path (within the package's `APIRouter`). If `None`,
                the decorated function's name is used as the path.
        """
        action_module = action.__module__
        action_name = action.__name__
        module = sys.modules[action_module]
        module_actions: ActionDescriptors | None = getattr(module, _actions_variable, None)
        if module_actions is None:
            module_actions = {}
            setattr(module, _actions_variable, module_actions)

        if path is None:
            path = f"/{action_name}"

        route_args["name"] = f"{action_module}.{action_name}"
        # Use the Action tag if no tags were set by the user.
        route_args["tags"] = ["Action"] if tags is None else tags
        route_args["response_model"] = None  # Don't generate a response schema.

        # Register the action.
        module_actions[path] = ActionDescriptor(
            action=action,
            route_args=route_args,
            use_layout=use_layout,
            metadata=metadata,
        )

get(path=None, *, use_layout=False, metadata=None, dependencies=None, deprecated=None, tags=None) classmethod

Decorator for registering an action with an HTTP GET method.

Corresponding FastAPI route decorator: APIRouter.get().

Parameters:

Name Type Description Default
use_layout bool

Whether to render the action's return value in the containing package's layout (same as a page).

False
metadata MetadataMappingOrDependency | None

Metadata mapping or dependency for the action. The equivalent of page metadata for actions.

None
path str | None

The action's path (within the package's APIRouter). If None, the decorated function's name is used as the path.

None
Source code in holm/module_options/_actions.py
@classmethod
def get(
    cls,
    path: str | None = None,
    *,
    use_layout: bool = False,
    metadata: MetadataMappingOrDependency | None = None,
    dependencies: Sequence[DependsParam] | None = None,
    deprecated: bool | None = None,
    tags: list[str | Enum] | None = None,
) -> ActionDependencyDecorator:
    """
    Decorator for registering an action with an HTTP GET method.

    Corresponding FastAPI route decorator: `APIRouter.get()`.

    Arguments:
        use_layout: Whether to render the action's return value in the
            containing package's layout (same as a page).
        metadata: Metadata mapping or dependency for the action. The equivalent
            of page metadata for actions.
        path: The action's path (within the package's `APIRouter`). If `None`,
            the decorated function's name is used as the path.
    """

    def decorator(func: ActionDependency) -> ActionDependency:
        cls._register_action(
            func,
            use_layout=use_layout,
            metadata=metadata,
            path=path,
            dependencies=dependencies,
            deprecated=deprecated,
            methods=("GET",),
            tags=tags,
        )
        return func

    return decorator

post(path=None, *, use_layout=False, metadata=None, dependencies=None, deprecated=None, tags=None) classmethod

Decorator for registering an action with an HTTP POST method.

Corresponding FastAPI route decorator: APIRouter.post().

Parameters:

Name Type Description Default
use_layout bool

Whether to render the action's return value in the containing package's layout (same as a page).

False
metadata MetadataMappingOrDependency | None

Metadata mapping or dependency for the action. The equivalent of page metadata for actions.

None
path str | None

The action's path (within the package's APIRouter). If None, the decorated function's name is used as the path.

None
Source code in holm/module_options/_actions.py
@classmethod
def post(
    cls,
    path: str | None = None,
    *,
    use_layout: bool = False,
    metadata: MetadataMappingOrDependency | None = None,
    dependencies: Sequence[DependsParam] | None = None,
    deprecated: bool | None = None,
    tags: list[str | Enum] | None = None,
) -> ActionDependencyDecorator:
    """
    Decorator for registering an action with an HTTP POST method.

    Corresponding FastAPI route decorator: `APIRouter.post()`.

    Arguments:
        use_layout: Whether to render the action's return value in the
            containing package's layout (same as a page).
        metadata: Metadata mapping or dependency for the action. The equivalent
            of page metadata for actions.
        path: The action's path (within the package's `APIRouter`). If `None`,
            the decorated function's name is used as the path.
    """

    def decorator(func: ActionDependency) -> ActionDependency:
        cls._register_action(
            func,
            use_layout=use_layout,
            metadata=metadata,
            path=path,
            dependencies=dependencies,
            deprecated=deprecated,
            methods=("POST",),
            tags=tags,
        )
        return func

    return decorator

put(path=None, *, use_layout=False, metadata=None, dependencies=None, deprecated=None, tags=None) classmethod

Decorator for registering an action with an HTTP PUT method.

Corresponding FastAPI route decorator: APIRouter.put().

Parameters:

Name Type Description Default
use_layout bool

Whether to render the action's return value in the containing package's layout (same as a page).

False
metadata MetadataMappingOrDependency | None

Metadata mapping or dependency for the action. The equivalent of page metadata for actions.

None
path str | None

The action's path (within the package's APIRouter). If None, the decorated function's name is used as the path.

None
Source code in holm/module_options/_actions.py
@classmethod
def put(
    cls,
    path: str | None = None,
    *,
    use_layout: bool = False,
    metadata: MetadataMappingOrDependency | None = None,
    dependencies: Sequence[DependsParam] | None = None,
    deprecated: bool | None = None,
    tags: list[str | Enum] | None = None,
) -> ActionDependencyDecorator:
    """
    Decorator for registering an action with an HTTP PUT method.

    Corresponding FastAPI route decorator: `APIRouter.put()`.

    Arguments:
        use_layout: Whether to render the action's return value in the
            containing package's layout (same as a page).
        metadata: Metadata mapping or dependency for the action. The equivalent
            of page metadata for actions.
        path: The action's path (within the package's `APIRouter`). If `None`,
            the decorated function's name is used as the path.
    """

    def decorator(func: ActionDependency) -> ActionDependency:
        cls._register_action(
            func,
            use_layout=use_layout,
            metadata=metadata,
            path=path,
            dependencies=dependencies,
            deprecated=deprecated,
            methods=("PUT",),
            tags=tags,
        )
        return func

    return decorator

patch(path=None, *, use_layout=False, metadata=None, dependencies=None, deprecated=None, tags=None) classmethod

Decorator for registering an action with an HTTP PATCH method.

Corresponding FastAPI route decorator: APIRouter.patch().

Parameters:

Name Type Description Default
use_layout bool

Whether to render the action's return value in the containing package's layout (same as a page).

False
metadata MetadataMappingOrDependency | None

Metadata mapping or dependency for the action. The equivalent of page metadata for actions.

None
path str | None

The action's path (within the package's APIRouter). If None, the decorated function's name is used as the path.

None
Source code in holm/module_options/_actions.py
@classmethod
def patch(
    cls,
    path: str | None = None,
    *,
    use_layout: bool = False,
    metadata: MetadataMappingOrDependency | None = None,
    dependencies: Sequence[DependsParam] | None = None,
    deprecated: bool | None = None,
    tags: list[str | Enum] | None = None,
) -> ActionDependencyDecorator:
    """
    Decorator for registering an action with an HTTP PATCH method.

    Corresponding FastAPI route decorator: `APIRouter.patch()`.

    Arguments:
        use_layout: Whether to render the action's return value in the
            containing package's layout (same as a page).
        metadata: Metadata mapping or dependency for the action. The equivalent
            of page metadata for actions.
        path: The action's path (within the package's `APIRouter`). If `None`,
            the decorated function's name is used as the path.
    """

    def decorator(func: ActionDependency) -> ActionDependency:
        cls._register_action(
            func,
            use_layout=use_layout,
            metadata=metadata,
            path=path,
            dependencies=dependencies,
            deprecated=deprecated,
            methods=("PATCH",),
            tags=tags,
        )
        return func

    return decorator

delete(path=None, *, use_layout=False, metadata=None, dependencies=None, deprecated=None, tags=None) classmethod

Decorator for registering an action with an HTTP DELETE method.

Corresponding FastAPI route decorator: APIRouter.delete().

Parameters:

Name Type Description Default
use_layout bool

Whether to render the action's return value in the containing package's layout (same as a page).

False
metadata MetadataMappingOrDependency | None

Metadata mapping or dependency for the action. The equivalent of page metadata for actions.

None
path str | None

The action's path (within the package's APIRouter). If None, the decorated function's name is used as the path.

None
Source code in holm/module_options/_actions.py
@classmethod
def delete(
    cls,
    path: str | None = None,
    *,
    use_layout: bool = False,
    metadata: MetadataMappingOrDependency | None = None,
    dependencies: Sequence[DependsParam] | None = None,
    deprecated: bool | None = None,
    tags: list[str | Enum] | None = None,
) -> ActionDependencyDecorator:
    """
    Decorator for registering an action with an HTTP DELETE method.

    Corresponding FastAPI route decorator: `APIRouter.delete()`.

    Arguments:
        use_layout: Whether to render the action's return value in the
            containing package's layout (same as a page).
        metadata: Metadata mapping or dependency for the action. The equivalent
            of page metadata for actions.
        path: The action's path (within the package's `APIRouter`). If `None`,
            the decorated function's name is used as the path.
    """

    def decorator(func: ActionDependency) -> ActionDependency:
        cls._register_action(
            func,
            use_layout=use_layout,
            metadata=metadata,
            path=path,
            dependencies=dependencies,
            deprecated=deprecated,
            methods=("DELETE",),
            tags=tags,
        )
        return func

    return decorator

__call__(path=None, *, use_layout=False, metadata=None, methods=None, dependencies=None, deprecated=None, tags=None) classmethod

Decorator for registering an action with arbitrary HTTP methods.

Corresponding FastAPI route decorator: APIRouter.api_route().

Parameters:

Name Type Description Default
use_layout bool

Whether to render the action's return value in the containing package's layout (same as a page).

False
metadata MetadataMappingOrDependency | None

Metadata mapping or dependency for the action. The equivalent of page metadata for actions.

None
path str | None

The action's path (within the package's APIRouter). If None, the decorated function's name is used as the path.

None
Source code in holm/module_options/_actions.py
@classmethod
def __call__(
    cls,
    path: str | None = None,
    *,
    use_layout: bool = False,
    metadata: MetadataMappingOrDependency | None = None,
    methods: Collection[HTTPMethod] | None = None,
    dependencies: Sequence[DependsParam] | None = None,
    deprecated: bool | None = None,
    tags: list[str | Enum] | None = None,
) -> ActionDependencyDecorator:
    """
    Decorator for registering an action with arbitrary HTTP `methods`.

    Corresponding FastAPI route decorator: `APIRouter.api_route()`.

    Arguments:
        use_layout: Whether to render the action's return value in the
            containing package's layout (same as a page).
        metadata: Metadata mapping or dependency for the action. The equivalent
            of page metadata for actions.
        path: The action's path (within the package's `APIRouter`). If `None`,
            the decorated function's name is used as the path.
    """

    def decorator(func: ActionDependency) -> ActionDependency:
        cls._register_action(
            func,
            use_layout=use_layout,
            metadata=metadata,
            path=path,
            dependencies=dependencies,
            deprecated=deprecated,
            methods=methods,
            tags=tags,
        )
        return func

    return decorator

holm.without_layout dataclass

Marker that signals that the component it contains should not be wrapped by the application in any parent layouts.

This utility must only be used as a return value wrapper in application components whose return value could be wrapped in a parent layout by holm. For example pages, submit handlers, layouts.

Attempting to render an instance of this class results in a RuntimeError. The only reason it implements the htmy() method is to make static code analysis tools accept it as an htmy.Component.

Source code in holm/modules/_layout.py
@dataclass(frozen=True, slots=True)
class without_layout:
    """
    Marker that signals that the component it contains should not be
    wrapped by the application in any parent layouts.

    This utility must only be used as a return value wrapper in application
    components whose return value could be wrapped in a parent layout by
    `holm`. For example pages, submit handlers, layouts.

    Attempting to render an instance of this class results in a `RuntimeError`.
    The only reason it implements the `htmy()` method is to make static code
    analysis tools accept it as an `htmy.Component`.
    """

    component: Component
    """The wrapped component."""

    def htmy(self, _: Any) -> Component:
        raise RuntimeError(f"{type(self).__name__} must never be part of the htmy component tree!")

holm.ErrorHandlerMapping = Mapping[type[Exception] | int, FastAPIErrorHandler] module-attribute

Mapping type whose keys are exception types or HTTP status codes, and the corresponding values are FastAPI error handlers.