Skip to content

Plugins

A plugin is a package that declares an entry point in the hyperadmin.plugins group and provides an object that satisfies the Plugin protocol. Admin discovers installed plugins, validates their settings and calls on_register(admin) before the admin is mounted.

# the plugin's pyproject.toml
[project.entry-points."hyperadmin.plugins"]
reports = "my_reports.plugin:ReportsPlugin"
from fastapi import APIRouter

from hyperadmin import Admin


class ReportsPlugin:
    name = "reports"

    def on_register(self, admin: Admin) -> None:
        router = APIRouter()
        admin.plugins.add_page(self, router, prefix="/reports")
        admin.plugins.add_nav_entry(self, label="Reports", url_name="reports-index")
        admin.plugins.add_permission(self, "view_report_sales")

From on_register a plugin may call add_page, add_nav_entry, add_template_dir, set_static_dir, add_permission and set_home_page. These are the public registry methods (see What is public API); the other methods of PluginRegistry are used by Admin itself. Pass disabled_plugins= or set HYPERADMIN_DISABLED_PLUGINS to skip a plugin, and plugin_settings= to configure one.

Lifecycle hooks

LIFECYCLE_HOOKS lists the names of the lifecycle hooks a plugin may implement as methods. HyperAdmin calls them with keyword arguments only, so write them to accept extra keyword arguments (**kwargs). A hook that raises is logged on the hyperadmin.core.plugins logger and skipped; it never breaks the request or the other plugins. When each hook fires is described in the hook reference.

Hook Keyword arguments
on_model_register admin, model, options
on_before_create / on_after_create admin, model, data / admin, model, instance
on_before_update / on_after_update admin, model, pk, data / admin, model, instance
on_before_delete / on_after_delete admin, model, pk
on_before_adapter_call / on_after_adapter_call admin, model, op, kwargs / admin, model, op, result, error
on_validation_error admin, model, field_errors
on_auth_event admin, event, user, username, request (and model for permission_denied)

API Reference

hyperadmin.core.plugins.Plugin

Bases: Protocol

What every plugin provides. All lifecycle hooks are optional methods.

A plugin may also define settings_model (a pydantic model class); the registry validates the operator's settings into it before on_register.

Source code in src/hyperadmin/core/plugins.py
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
@runtime_checkable
class Plugin(Protocol):
    """What every plugin provides. All lifecycle hooks are optional methods.

    A plugin may also define ``settings_model`` (a pydantic model class); the
    registry validates the operator's settings into it before ``on_register``.
    """

    name: str

    def on_register(self, admin: Any) -> None:
        """Contribute pages, nav entries, templates, static files and permissions.

        Called once per ``Admin``, in plugin order, before the admin is mounted. Use the
        ``add_*`` and ``set_static_dir`` methods of ``admin.plugins`` (a ``PluginRegistry``).
        """

on_register(admin)

Contribute pages, nav entries, templates, static files and permissions.

Called once per Admin, in plugin order, before the admin is mounted. Use the add_* and set_static_dir methods of admin.plugins (a PluginRegistry).

Source code in src/hyperadmin/core/plugins.py
77
78
79
80
81
82
def on_register(self, admin: Any) -> None:
    """Contribute pages, nav entries, templates, static files and permissions.

    Called once per ``Admin``, in plugin order, before the admin is mounted. Use the
    ``add_*`` and ``set_static_dir`` methods of ``admin.plugins`` (a ``PluginRegistry``).
    """

hyperadmin.core.plugins.PluginRegistry

Discovered plugins, their settings, collected UI seams and hook dispatch.

Source code in src/hyperadmin/core/plugins.py
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
class PluginRegistry:
    """Discovered plugins, their settings, collected UI seams and hook dispatch."""

    def __init__(self) -> None:
        self._plugins: dict[str, Plugin] = {}
        self._origins: dict[str, str] = {}
        self._settings: dict[str, Any] = {}
        self._contributions: dict[str, _Contributions] = {}
        self._skipped: dict[str, SkipReason] = {}
        self._handlers: dict[str, list[tuple[str, Callable[..., Any]]]] = {}
        self._registering: str | None = None

    # -- discovery & registration -------------------------------------------------

    @classmethod
    def discover(
        cls,
        *,
        admin: Any,
        disabled: Iterable[str] = (),
        settings: Mapping[str, Mapping[str, Any]] | None = None,
    ) -> PluginRegistry:
        """Load every ``hyperadmin.plugins`` entry point, isolating failures.

        Entry points are processed sorted by ``(name, value)`` so the order is
        deterministic; a later entry point reusing a name is skipped.
        """
        registry = cls()
        registry.load_entry_points(admin=admin, disabled=disabled, settings=settings)
        return registry

    def load_entry_points(
        self,
        *,
        admin: Any,
        disabled: Iterable[str] = (),
        settings: Mapping[str, Mapping[str, Any]] | None = None,
    ) -> None:
        """Like :meth:`discover`, into this registry.

        ``Admin`` assigns ``admin.plugins`` first and then loads into it, so a
        plugin's ``on_register`` can call ``admin.plugins.add_*``.
        """
        skip = set(disabled) | parse_disabled_env(os.environ.get(DISABLED_PLUGINS_ENV))
        settings = settings or {}
        eps = sorted(
            entry_points(group=PLUGIN_ENTRY_POINT_GROUP), key=lambda ep: (ep.name, ep.value)
        )
        seen: dict[str, str] = {}
        for ep in eps:
            if ep.name in seen:
                logger.warning(
                    "plugin %r from %s skipped: name already taken by %s",
                    ep.name,
                    ep.value,
                    seen[ep.name],
                    extra={"plugin": ep.name, "plugin_entry_point": ep.value},
                )
                continue
            seen[ep.name] = ep.value
            if ep.name in skip:
                self._skipped[ep.name] = "disabled"
                continue
            plugin = self._load(ep)
            if plugin is None:
                continue
            self.register(plugin, admin=admin, settings=settings.get(ep.name), origin=ep.value)

    def _load(self, ep: EntryPoint) -> Plugin | None:
        try:
            obj = ep.load()
            plugin = obj() if inspect.isclass(obj) else obj
        except Exception:
            logger.exception(
                "plugin %r failed to load",
                ep.name,
                extra={"plugin": ep.name, "plugin_entry_point": ep.value},
            )
            self._skipped[ep.name] = "load_error"
            return None
        if not isinstance(plugin, Plugin) or plugin.name != ep.name:
            logger.error(
                "plugin %r skipped: %s is not a Plugin whose name matches the entry point",
                ep.name,
                ep.value,
                extra={"plugin": ep.name, "plugin_entry_point": ep.value},
            )
            self._skipped[ep.name] = "invalid"
            return None
        return plugin

    def register(
        self,
        plugin: Plugin,
        *,
        admin: Any,
        settings: Mapping[str, Any] | None = None,
        origin: str | None = None,
    ) -> bool:
        """Validate settings, run ``on_register`` and keep the plugin on success.

        Any failure is logged and rolls back everything the plugin contributed;
        returns whether the plugin was registered.
        """
        name = plugin.name
        if not isinstance(name, str) or not _NAME_RE.match(name) or name in self._plugins:
            logger.error(
                "plugin %r skipped: invalid or duplicate name", name, extra={"plugin": name}
            )
            return False
        self._origins[name] = origin or f"{type(plugin).__module__}:{type(plugin).__qualname__}"
        self._contributions[name] = _Contributions()
        self._registering = name
        try:
            settings_model: type[BaseModel] | None = getattr(plugin, "settings_model", None)
            if settings_model is not None:
                self._settings[name] = settings_model(**(settings or {}))
            plugin.on_register(admin)
        except Exception:
            logger.exception(
                "plugin %r failed to register", name, extra={"plugin": name, "hook": "on_register"}
            )
            self._contributions.pop(name)
            self._settings.pop(name, None)
            self._skipped[name] = "register_error"
            return False
        finally:
            self._registering = None
        self._plugins[name] = plugin
        self._handlers.clear()
        return True

    # -- mapping-like access ------------------------------------------------------

    def __contains__(self, name: object) -> bool:
        return name in self._plugins

    def __getitem__(self, name: str) -> Plugin:
        return self._plugins[name]

    def __bool__(self) -> bool:
        return bool(self._plugins)

    def __len__(self) -> int:
        return len(self._plugins)

    def names(self) -> list[str]:
        """Registered plugin names, in registration order."""
        return list(self._plugins)

    def origin(self, name: str) -> str:
        """Import path (entry-point value) a plugin was loaded from."""
        return self._origins[name]

    @property
    def skipped(self) -> dict[str, SkipReason]:
        """Plugins that were found but not registered, with the reason."""
        return dict(self._skipped)

    def settings(self, name: str) -> Any:
        """The validated ``settings_model`` instance of a plugin, or ``None``."""
        return self._settings.get(name)

    # -- UI seams (callable only from the plugin's own on_register) ---------------

    def _contributing(self, plugin: Plugin) -> _Contributions:
        if self._registering is None or plugin.name != self._registering:
            raise PluginError(
                f"plugin {plugin.name!r} may only register UI seams from its own on_register()"
            )
        return self._contributions[plugin.name]

    def _all(self) -> Iterable[_Contributions]:
        return (self._contributions[name] for name in self._plugins)

    def add_page(self, plugin: Plugin, router: Any, *, prefix: str | None = None) -> PluginPage:
        """Mount ``router`` (a FastAPI ``APIRouter``) under ``prefix`` in the admin.

        ``prefix`` defaults to ``/<plugin name>`` and must be unique across plugins.
        """
        contrib = self._contributing(plugin)
        prefix = prefix if prefix is not None else f"/{plugin.name}"
        if not _PREFIX_RE.match(prefix):
            raise PluginError(f"invalid page prefix {prefix!r}")
        if not hasattr(router, "routes"):
            raise PluginError(f"{router!r} is not a router")
        taken = {p.prefix for c in (*self._all(), contrib) for p in c.pages}
        if prefix in taken:
            raise PluginError(f"page prefix {prefix!r} is already used by another plugin")
        page = PluginPage(plugin=plugin.name, router=router, prefix=prefix)
        contrib.pages.append(page)
        return page

    def add_nav_entry(  # noqa: PLR0913 - one keyword per NavEntry field
        self,
        plugin: Plugin,
        *,
        label: str,
        url_name: str,
        icon: str | None = None,
        permission: str | None = None,
        section: str | None = None,
        order: int = 0,
        url_params: Mapping[str, Any] | None = None,
        testid: str | None = None,
    ) -> NavEntry:
        """Add a sidebar link; ``url_name`` is resolved in the ``hyperadmin:`` namespace.

        ``testid`` names the link for tests when several entries share a
        ``url_name`` (one per ``url_params``); by default it is derived from it.
        """
        contrib = self._contributing(plugin)
        if not label or not url_name:
            raise PluginError("nav entry needs a label and a url_name")
        entry = NavEntry(
            plugin=plugin.name,
            label=label,
            url_name=url_name,
            icon=icon,
            permission=permission,
            section=section,
            order=order,
            url_params=dict(url_params or {}),
            testid=testid,
        )
        contrib.nav_entries.append(entry)
        return entry

    def add_template_dir(self, plugin: Plugin, path: str | os.PathLike[str]) -> PluginTemplateDir:
        """Add a template search path (searched after core and host templates)."""
        contrib = self._contributing(plugin)
        resolved = Path(path).resolve()
        if not resolved.is_dir():
            raise PluginError(f"template dir {resolved} does not exist")
        template_dir = PluginTemplateDir(plugin=plugin.name, path=resolved)
        contrib.template_dirs.append(template_dir)
        return template_dir

    def set_static_dir(self, plugin: Plugin, path: str | os.PathLike[str]) -> PluginStaticDir:
        """Serve ``path`` under ``{prefix}/static/plugins/<plugin name>/`` (one per plugin)."""
        contrib = self._contributing(plugin)
        resolved = Path(path).resolve()
        if not resolved.is_dir():
            raise PluginError(f"static dir {resolved} does not exist")
        if contrib.static_dir is not None:
            raise PluginError(f"plugin {plugin.name!r} already has a static dir")
        contrib.static_dir = PluginStaticDir(plugin=plugin.name, path=resolved)
        return contrib.static_dir

    def add_permission(
        self, plugin: Plugin, codename: str, name: str | None = None
    ) -> PluginPermission:
        """Declare a permission codename so it shows in the permission system."""
        contrib = self._contributing(plugin)
        if not _CODENAME_RE.match(codename):
            raise PluginError(f"invalid permission codename {codename!r}")
        taken = {p.codename for c in (*self._all(), contrib) for p in c.permissions}
        if codename in taken:
            raise PluginError(f"permission {codename!r} is already declared")
        perm = PluginPermission(
            plugin=plugin.name,
            codename=codename,
            name=name or f"Can {codename.replace('_', ' ')}",
        )
        contrib.permissions.append(perm)
        return perm

    def set_home_page(self, plugin: Plugin, endpoint: HomePageEndpoint) -> PluginHomePage:
        """Serve ``endpoint`` at the admin index ``{prefix}/`` (one plugin per admin).

        ``endpoint`` is ``async (request) -> Response``. The index route keeps its name
        (``admin-dashboard``) and falls back to the welcome page if the endpoint raises
        anything but an ``HTTPException``.

        Raises:
            PluginError: If a home page is already set, or outside ``on_register()``.
        """
        contrib = self._contributing(plugin)
        if not callable(endpoint):
            raise PluginError(f"{endpoint!r} is not a home page endpoint")
        taken = next((c.home_page for c in (*self._all(), contrib) if c.home_page), None)
        if taken is not None:
            raise PluginError(f"the admin home page is already set by plugin {taken.plugin!r}")
        contrib.home_page = PluginHomePage(plugin=plugin.name, endpoint=endpoint)
        return contrib.home_page

    # -- collected seams (consumed by Admin wiring) -------------------------------

    @property
    def pages(self) -> list[PluginPage]:
        return [p for c in self._all() for p in c.pages]

    @property
    def nav_entries(self) -> list[NavEntry]:
        """Nav entries sorted by ``(order, label)``; ties keep plugin order."""
        entries = [e for c in self._all() for e in c.nav_entries]
        return sorted(entries, key=lambda e: (e.order, e.label))

    @property
    def template_dirs(self) -> list[PluginTemplateDir]:
        return [d for c in self._all() for d in c.template_dirs]

    @property
    def static_dirs(self) -> list[PluginStaticDir]:
        return [c.static_dir for c in self._all() if c.static_dir is not None]

    @property
    def permissions(self) -> list[PluginPermission]:
        return [p for c in self._all() for p in c.permissions]

    @property
    def home_page(self) -> PluginHomePage | None:
        """The plugin endpoint serving the admin index, or ``None`` for the welcome page."""
        return next((c.home_page for c in self._all() if c.home_page is not None), None)

    # -- lifecycle hooks ----------------------------------------------------------

    def _handlers_for(self, hook: str) -> list[tuple[str, Callable[..., Any]]]:
        if hook not in LIFECYCLE_HOOKS:
            raise ValueError(f"unknown plugin hook {hook!r}")
        handlers = self._handlers.get(hook)
        if handlers is None:
            handlers = []
            for name, plugin in self._plugins.items():
                handler = getattr(plugin, hook, None)
                if not callable(handler):
                    continue
                if inspect.iscoroutinefunction(handler):
                    logger.error(
                        "plugin %r: async hook %s is not supported; ignored",
                        name,
                        hook,
                        extra={"plugin": name, "hook": hook},
                    )
                    continue
                handlers.append((name, handler))
            self._handlers[hook] = handlers
        return handlers

    def has_handlers(self, hook: str) -> bool:
        """Whether any plugin implements ``hook`` (hot-path short-circuit)."""
        return bool(self._handlers_for(hook))

    def dispatch_hook(self, hook: str, /, **kwargs: Any) -> None:
        """Call every plugin's ``hook`` in plugin order; exceptions are logged, not raised."""
        for name, handler in self._handlers_for(hook):
            try:
                handler(**kwargs)
            except Exception:  # noqa: PERF203 - per-plugin isolation is the contract
                logger.exception(
                    "plugin %r hook %s raised", name, hook, extra={"plugin": name, "hook": hook}
                )

home_page property

The plugin endpoint serving the admin index, or None for the welcome page.

nav_entries property

Nav entries sorted by (order, label); ties keep plugin order.

skipped property

Plugins that were found but not registered, with the reason.

add_nav_entry(plugin, *, label, url_name, icon=None, permission=None, section=None, order=0, url_params=None, testid=None)

Add a sidebar link; url_name is resolved in the hyperadmin: namespace.

testid names the link for tests when several entries share a url_name (one per url_params); by default it is derived from it.

Source code in src/hyperadmin/core/plugins.py
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
def add_nav_entry(  # noqa: PLR0913 - one keyword per NavEntry field
    self,
    plugin: Plugin,
    *,
    label: str,
    url_name: str,
    icon: str | None = None,
    permission: str | None = None,
    section: str | None = None,
    order: int = 0,
    url_params: Mapping[str, Any] | None = None,
    testid: str | None = None,
) -> NavEntry:
    """Add a sidebar link; ``url_name`` is resolved in the ``hyperadmin:`` namespace.

    ``testid`` names the link for tests when several entries share a
    ``url_name`` (one per ``url_params``); by default it is derived from it.
    """
    contrib = self._contributing(plugin)
    if not label or not url_name:
        raise PluginError("nav entry needs a label and a url_name")
    entry = NavEntry(
        plugin=plugin.name,
        label=label,
        url_name=url_name,
        icon=icon,
        permission=permission,
        section=section,
        order=order,
        url_params=dict(url_params or {}),
        testid=testid,
    )
    contrib.nav_entries.append(entry)
    return entry

add_page(plugin, router, *, prefix=None)

Mount router (a FastAPI APIRouter) under prefix in the admin.

prefix defaults to /<plugin name> and must be unique across plugins.

Source code in src/hyperadmin/core/plugins.py
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
def add_page(self, plugin: Plugin, router: Any, *, prefix: str | None = None) -> PluginPage:
    """Mount ``router`` (a FastAPI ``APIRouter``) under ``prefix`` in the admin.

    ``prefix`` defaults to ``/<plugin name>`` and must be unique across plugins.
    """
    contrib = self._contributing(plugin)
    prefix = prefix if prefix is not None else f"/{plugin.name}"
    if not _PREFIX_RE.match(prefix):
        raise PluginError(f"invalid page prefix {prefix!r}")
    if not hasattr(router, "routes"):
        raise PluginError(f"{router!r} is not a router")
    taken = {p.prefix for c in (*self._all(), contrib) for p in c.pages}
    if prefix in taken:
        raise PluginError(f"page prefix {prefix!r} is already used by another plugin")
    page = PluginPage(plugin=plugin.name, router=router, prefix=prefix)
    contrib.pages.append(page)
    return page

add_permission(plugin, codename, name=None)

Declare a permission codename so it shows in the permission system.

Source code in src/hyperadmin/core/plugins.py
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
def add_permission(
    self, plugin: Plugin, codename: str, name: str | None = None
) -> PluginPermission:
    """Declare a permission codename so it shows in the permission system."""
    contrib = self._contributing(plugin)
    if not _CODENAME_RE.match(codename):
        raise PluginError(f"invalid permission codename {codename!r}")
    taken = {p.codename for c in (*self._all(), contrib) for p in c.permissions}
    if codename in taken:
        raise PluginError(f"permission {codename!r} is already declared")
    perm = PluginPermission(
        plugin=plugin.name,
        codename=codename,
        name=name or f"Can {codename.replace('_', ' ')}",
    )
    contrib.permissions.append(perm)
    return perm

add_template_dir(plugin, path)

Add a template search path (searched after core and host templates).

Source code in src/hyperadmin/core/plugins.py
393
394
395
396
397
398
399
400
401
def add_template_dir(self, plugin: Plugin, path: str | os.PathLike[str]) -> PluginTemplateDir:
    """Add a template search path (searched after core and host templates)."""
    contrib = self._contributing(plugin)
    resolved = Path(path).resolve()
    if not resolved.is_dir():
        raise PluginError(f"template dir {resolved} does not exist")
    template_dir = PluginTemplateDir(plugin=plugin.name, path=resolved)
    contrib.template_dirs.append(template_dir)
    return template_dir

discover(*, admin, disabled=(), settings=None) classmethod

Load every hyperadmin.plugins entry point, isolating failures.

Entry points are processed sorted by (name, value) so the order is deterministic; a later entry point reusing a name is skipped.

Source code in src/hyperadmin/core/plugins.py
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
@classmethod
def discover(
    cls,
    *,
    admin: Any,
    disabled: Iterable[str] = (),
    settings: Mapping[str, Mapping[str, Any]] | None = None,
) -> PluginRegistry:
    """Load every ``hyperadmin.plugins`` entry point, isolating failures.

    Entry points are processed sorted by ``(name, value)`` so the order is
    deterministic; a later entry point reusing a name is skipped.
    """
    registry = cls()
    registry.load_entry_points(admin=admin, disabled=disabled, settings=settings)
    return registry

dispatch_hook(hook, /, **kwargs)

Call every plugin's hook in plugin order; exceptions are logged, not raised.

Source code in src/hyperadmin/core/plugins.py
508
509
510
511
512
513
514
515
516
def dispatch_hook(self, hook: str, /, **kwargs: Any) -> None:
    """Call every plugin's ``hook`` in plugin order; exceptions are logged, not raised."""
    for name, handler in self._handlers_for(hook):
        try:
            handler(**kwargs)
        except Exception:  # noqa: PERF203 - per-plugin isolation is the contract
            logger.exception(
                "plugin %r hook %s raised", name, hook, extra={"plugin": name, "hook": hook}
            )

has_handlers(hook)

Whether any plugin implements hook (hot-path short-circuit).

Source code in src/hyperadmin/core/plugins.py
504
505
506
def has_handlers(self, hook: str) -> bool:
    """Whether any plugin implements ``hook`` (hot-path short-circuit)."""
    return bool(self._handlers_for(hook))

load_entry_points(*, admin, disabled=(), settings=None)

Like :meth:discover, into this registry.

Admin assigns admin.plugins first and then loads into it, so a plugin's on_register can call admin.plugins.add_*.

Source code in src/hyperadmin/core/plugins.py
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
def load_entry_points(
    self,
    *,
    admin: Any,
    disabled: Iterable[str] = (),
    settings: Mapping[str, Mapping[str, Any]] | None = None,
) -> None:
    """Like :meth:`discover`, into this registry.

    ``Admin`` assigns ``admin.plugins`` first and then loads into it, so a
    plugin's ``on_register`` can call ``admin.plugins.add_*``.
    """
    skip = set(disabled) | parse_disabled_env(os.environ.get(DISABLED_PLUGINS_ENV))
    settings = settings or {}
    eps = sorted(
        entry_points(group=PLUGIN_ENTRY_POINT_GROUP), key=lambda ep: (ep.name, ep.value)
    )
    seen: dict[str, str] = {}
    for ep in eps:
        if ep.name in seen:
            logger.warning(
                "plugin %r from %s skipped: name already taken by %s",
                ep.name,
                ep.value,
                seen[ep.name],
                extra={"plugin": ep.name, "plugin_entry_point": ep.value},
            )
            continue
        seen[ep.name] = ep.value
        if ep.name in skip:
            self._skipped[ep.name] = "disabled"
            continue
        plugin = self._load(ep)
        if plugin is None:
            continue
        self.register(plugin, admin=admin, settings=settings.get(ep.name), origin=ep.value)

names()

Registered plugin names, in registration order.

Source code in src/hyperadmin/core/plugins.py
311
312
313
def names(self) -> list[str]:
    """Registered plugin names, in registration order."""
    return list(self._plugins)

origin(name)

Import path (entry-point value) a plugin was loaded from.

Source code in src/hyperadmin/core/plugins.py
315
316
317
def origin(self, name: str) -> str:
    """Import path (entry-point value) a plugin was loaded from."""
    return self._origins[name]

register(plugin, *, admin, settings=None, origin=None)

Validate settings, run on_register and keep the plugin on success.

Any failure is logged and rolls back everything the plugin contributed; returns whether the plugin was registered.

Source code in src/hyperadmin/core/plugins.py
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
def register(
    self,
    plugin: Plugin,
    *,
    admin: Any,
    settings: Mapping[str, Any] | None = None,
    origin: str | None = None,
) -> bool:
    """Validate settings, run ``on_register`` and keep the plugin on success.

    Any failure is logged and rolls back everything the plugin contributed;
    returns whether the plugin was registered.
    """
    name = plugin.name
    if not isinstance(name, str) or not _NAME_RE.match(name) or name in self._plugins:
        logger.error(
            "plugin %r skipped: invalid or duplicate name", name, extra={"plugin": name}
        )
        return False
    self._origins[name] = origin or f"{type(plugin).__module__}:{type(plugin).__qualname__}"
    self._contributions[name] = _Contributions()
    self._registering = name
    try:
        settings_model: type[BaseModel] | None = getattr(plugin, "settings_model", None)
        if settings_model is not None:
            self._settings[name] = settings_model(**(settings or {}))
        plugin.on_register(admin)
    except Exception:
        logger.exception(
            "plugin %r failed to register", name, extra={"plugin": name, "hook": "on_register"}
        )
        self._contributions.pop(name)
        self._settings.pop(name, None)
        self._skipped[name] = "register_error"
        return False
    finally:
        self._registering = None
    self._plugins[name] = plugin
    self._handlers.clear()
    return True

set_home_page(plugin, endpoint)

Serve endpoint at the admin index {prefix}/ (one plugin per admin).

endpoint is async (request) -> Response. The index route keeps its name (admin-dashboard) and falls back to the welcome page if the endpoint raises anything but an HTTPException.

Raises:

Type Description
PluginError

If a home page is already set, or outside on_register().

Source code in src/hyperadmin/core/plugins.py
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
def set_home_page(self, plugin: Plugin, endpoint: HomePageEndpoint) -> PluginHomePage:
    """Serve ``endpoint`` at the admin index ``{prefix}/`` (one plugin per admin).

    ``endpoint`` is ``async (request) -> Response``. The index route keeps its name
    (``admin-dashboard``) and falls back to the welcome page if the endpoint raises
    anything but an ``HTTPException``.

    Raises:
        PluginError: If a home page is already set, or outside ``on_register()``.
    """
    contrib = self._contributing(plugin)
    if not callable(endpoint):
        raise PluginError(f"{endpoint!r} is not a home page endpoint")
    taken = next((c.home_page for c in (*self._all(), contrib) if c.home_page), None)
    if taken is not None:
        raise PluginError(f"the admin home page is already set by plugin {taken.plugin!r}")
    contrib.home_page = PluginHomePage(plugin=plugin.name, endpoint=endpoint)
    return contrib.home_page

set_static_dir(plugin, path)

Serve path under {prefix}/static/plugins/<plugin name>/ (one per plugin).

Source code in src/hyperadmin/core/plugins.py
403
404
405
406
407
408
409
410
411
412
def set_static_dir(self, plugin: Plugin, path: str | os.PathLike[str]) -> PluginStaticDir:
    """Serve ``path`` under ``{prefix}/static/plugins/<plugin name>/`` (one per plugin)."""
    contrib = self._contributing(plugin)
    resolved = Path(path).resolve()
    if not resolved.is_dir():
        raise PluginError(f"static dir {resolved} does not exist")
    if contrib.static_dir is not None:
        raise PluginError(f"plugin {plugin.name!r} already has a static dir")
    contrib.static_dir = PluginStaticDir(plugin=plugin.name, path=resolved)
    return contrib.static_dir

settings(name)

The validated settings_model instance of a plugin, or None.

Source code in src/hyperadmin/core/plugins.py
324
325
326
def settings(self, name: str) -> Any:
    """The validated ``settings_model`` instance of a plugin, or ``None``."""
    return self._settings.get(name)

hyperadmin.core.plugins.PluginError

Bases: Exception

A plugin misused the registration API (bad argument, wrong time, conflict).

Source code in src/hyperadmin/core/plugins.py
63
64
class PluginError(Exception):
    """A plugin misused the registration API (bad argument, wrong time, conflict)."""

hyperadmin.core.plugins.LIFECYCLE_HOOKS = frozenset({'on_model_register', 'on_before_create', 'on_after_create', 'on_before_update', 'on_after_update', 'on_before_delete', 'on_after_delete', 'on_before_adapter_call', 'on_after_adapter_call', 'on_validation_error', 'on_auth_event'}) module-attribute