Ir para o conteúdo

tempest_fastapi_sdk.admin

O painel admin estilo Django: site, model admin, ações, políticas de acesso, auditoria e páginas.

« Admin, dados e API


AdminSite

AdminSite(
    title: str = "Admin",
    *,
    brand: str | None = None,
    index_subtitle: str | None = None,
    site_url: str | None = None,
    theme: AdminTheme | None = None,
    dashboard_cards: Sequence[MetricCard] = (),
    display_timezone: str | None = None,
    metrics_areas: Sequence[MetricsArea] = (),
    location_maps: Sequence[BRLocationMap] = (),
    locale: AdminLocale = DEFAULT_ADMIN_LOCALE,
    recent_activity: int | None = None,
)

Holds the set of :class:AdminModel configurations to expose.

Each project instantiates one site, registers its admin configurations (one at a time with :meth:register, or all at once with :meth:automap), and passes the site to :func:make_admin_router.

Attributes:

Name Type Description
title str

Branding shown in the page <title> and the dashboard heading.

brand str | None

Optional override for the centered header brand text. Falls back to :attr:title when unset — read it through :attr:brand_text.

index_subtitle str

Optional subtitle for the dashboard.

site_url str | None

Optional "View site" link rendered in the admin header.

theme AdminTheme

Typed appearance overrides (colors, logo, favicon, font, footer, dark mode). Defaults to a stock :class:AdminTheme, so the look is unchanged when omitted.

dashboard_cards list[MetricCard]

Business-metric cards (value / trend / partition) rendered at the top of the dashboard, each computed from the DB on load. Distinct from the system CPU/RAM/disk panel.

metrics_areas list[MetricsArea]

Indicator pages generated from a schema and a service, one card per field.

location_maps list[BRLocationMap]

Map pages of where a model's rows are in Brazil.

locale AdminLocale

Language of the panel's own text.

recent_activity int | None

Entries of the dashboard's recent activity feed, or None when the feed is off.

Initialize the site.

Parameters:

Name Type Description Default
title str

Branding text — used in the page <title> and the dashboard heading.

'Admin'
brand str | None

Optional text for the centered header brand. None (default) falls back to title, so existing sites keep their current header. Set it to show a distinct name (e.g. "servus-backend-admin") centered at the top of every page.

None
index_subtitle str | None

Dashboard and login subtitle. None (default) uses the catalog's "Site administration" in :attr:locale.

None
site_url str | None

Optional outbound link rendered in the admin header.

None
theme AdminTheme | None

Typed appearance overrides. None (default) uses a stock :class:AdminTheme, leaving the look identical to earlier versions.

None
dashboard_cards Sequence[MetricCard]

Business-metric cards rendered on the dashboard.

()
display_timezone str | None

IANA zone every registered model inherits for its datetime columns — the zone the operator reads and types in. A model that declares its own keeps it. None (default) leaves everything in UTC. The zone belongs to the panel rather than to any one table, which is why it is settable here instead of being repeated on every :class:AdminModel.

None
metrics_areas Sequence[MetricsArea]

Indicator pages, each generated from a schema and a service method with no arguments, listed under "Metrics" in the sidebar. Gated by the METRICS surface.

()
location_maps Sequence[BRLocationMap]

Map pages listed under "Maps" in the sidebar, each shading Brazil by a model's row count per state. Gated by VIEW on that model.

()
locale AdminLocale

Language of the panel's own text — labels, buttons, empty states, flash messages and the errors the router renders (see :mod:tempest_fastapi_sdk.admin.i18n). "en" (default) keeps the strings the panel always had; "pt-BR" renders Brazilian Portuguese. Text you configure (model and field names, verbose_name, action labels, title) is shown as given.

DEFAULT_ADMIN_LOCALE
recent_activity int | None

Show the last N changes of every registered model that declares audit_model on the dashboard, merged newest first, each linking to its row. None (default) leaves the feed off, because it costs queries on every dashboard load: one per audit table, one per audited model to keep only the rows the principal reaches, and one author lookup per distinct author. A model the principal may not VIEW is left out, and so is an entry whose row falls outside the model's row_scope (or no longer exists, on a scoped model), label included.

None

Raises:

Type Description
ValueError

When display_timezone is not a zone the host's tz database knows, or two metrics_areas (or two location_maps) share a URL slug, or locale is not one of :data:~tempest_fastapi_sdk.admin.i18n.ADMIN_LOCALES, or recent_activity is not a positive number.

brand_text property

brand_text: str

Return the centered header brand text.

Returns:

Name Type Description
str str

:attr:brand when set, otherwise :attr:title.

registry property

registry: dict[str, AdminModel[Any]]

Return a copy of the slug→admin mapping.

Returns:

Type Description
dict[str, AdminModel[Any]]

dict[str, AdminModel[Any]]: The current registry.

register

register(admin: AdminModel[Any]) -> AdminModel[Any]

Register admin against its model slug.

Example::

site.register(AdminModel(model=UserModel))

Parameters:

Name Type Description Default
admin AdminModel[Any]

The admin configuration instance.

required

Returns:

Type Description
AdminModel[Any]

AdminModel[Any]: The same instance (so the call can be

AdminModel[Any]

chained or assigned).

A model that declares no display_timezone of its own inherits the site's, so the panel reads and writes datetimes in one zone without every registration repeating it.

Raises:

Type Description
ValueError

When another admin is already registered under the same slug.

unregister

unregister(slug: str | type[BaseModel]) -> None

Remove a previously registered admin.

Parameters:

Name Type Description Default
slug str | type[BaseModel]

The slug to drop, or the model class, whose table name is the slug.

required

Raises:

Type Description
KeyError

When no admin is registered under slug.

get

get(slug: str | type[BaseModel]) -> AdminModel[Any] | None

Return the admin registered under slug, or None.

Example::

site.get(UserModel)
site.get("user")

Parameters:

Name Type Description Default
slug str | type[BaseModel]

The admin slug, or the model class, whose table name is the slug.

required

Returns:

Type Description
AdminModel[Any] | None

AdminModel[Any] | None: The configuration instance.

require

require(slug: str | type[BaseModel]) -> AdminModel[Any]

Return the admin registered under slug or raise.

Parameters:

Name Type Description Default
slug str | type[BaseModel]

The admin slug, or the model class, whose table name is the slug.

required

Returns:

Type Description
AdminModel[Any]

AdminModel[Any]: The configuration instance.

Raises:

Type Description
KeyError

When no admin matches the slug.

iter_models

iter_models() -> list[AdminModel[Any]]

Return registered admins ordered by display name.

Returns:

Type Description
list[AdminModel[Any]]

list[AdminModel[Any]]: Ordered admin instances.

automap

automap(
    source: str | ModuleType,
    *,
    exclude: Sequence[type[BaseModel] | str] = (),
    skip_registered: bool = True,
    **admin_kwargs: Any,
) -> list[AdminModel[Any]]

Register every concrete model found under source at once.

The batch counterpart to :meth:register: instead of writing one site.register(AdminModel(model=...)) per table, point this at the package that holds the ORM models and every concrete :class:~tempest_fastapi_sdk.BaseModel subclass is wrapped in a default :class:AdminModel and registered.

Example::

site = AdminSite(title="Servus", brand="servus-backend-admin")
site.automap("src.db.models")

Abstract bases (BaseUserModel and friends — no __tablename__) are skipped automatically. Models you want configured by hand can be registered first and left out here with skip_registered=True (the default), or hidden entirely via exclude.

Parameters:

Name Type Description Default
source str | ModuleType

Dotted module path (e.g. "src.db.models") or an already-imported module/package. Packages have their submodules swept too.

required
exclude Sequence[type[BaseModel] | str]

Models to skip — each entry is the model class, its class name, or its table name.

()
skip_registered bool

When True (default), a model whose slug is already registered is left untouched, so you can register a hand-tuned AdminModel first and let automap fill in the rest. When False, a collision raises ValueError (as :meth:register does).

True
**admin_kwargs Any

Forwarded to every AdminModel constructed here (e.g. page_size=50, can_delete=False). Applied uniformly — reach for per-model :meth:register when a model needs its own configuration.

{}

Returns:

Type Description
list[AdminModel[Any]]

list[AdminModel[Any]]: The admins newly registered by this

list[AdminModel[Any]]

call, ordered by table name.

Raises:

Type Description
ValueError

When skip_registered is False and a discovered model's slug is already registered.

AdminModel

AdminModel(
    model: type[ModelT],
    *,
    list_display: Sequence[FieldRef] | None = None,
    list_filter: Sequence[FieldRef] = (),
    search_fields: Sequence[FieldRef] = (),
    readonly_fields: Sequence[FieldRef] = (),
    ordering: OrderRef | None = None,
    page_size: int = 25,
    identity_field: FieldRef = "id",
    repository_class: type[BaseRepository[Any]] | None = None,
    verbose_name: str | None = None,
    verbose_name_plural: str | None = None,
    can_create: bool | None = None,
    can_edit: bool = True,
    can_delete: bool = True,
    can_import: bool = False,
    can_toggle_active: bool = True,
    actions: Sequence[AnyActionHandler] = (),
    upload_fields: Sequence[FieldRef] = (),
    upload_storage: UploadStorage | None = None,
    audit_model: type[BaseAuditLogModel] | None = None,
    autocomplete_fields: Sequence[FieldRef] = (),
    inlines: Sequence[Inline] = (),
    lenses: Sequence[Lens] = (),
    display_timezone: str | None = None,
    password_fields: Sequence[FieldRef] = (),
    password_policy: PasswordPolicy | None = None,
    exclude_fields: Sequence[FieldRef] = (),
    create_handler: AdminCreateHandler | None = None,
    choices: Mapping[FieldRef, ChoiceSource] | None = None,
    upload_accept: Mapping[FieldRef, Sequence[str]] | None = None,
    validate_edit: EditValidator | None = None,
    readonly_fields_for: ReadonlyFieldsFor | None = None,
    row_scope: AdminRowScope | None = None,
    m2m_fields: Sequence[FieldRef] = (),
    related_counts: Sequence[RelatedCount] = (),
    can_duplicate: bool = False,
    bulk_edit_fields: Sequence[FieldRef] = (),
    impersonate: AdminImpersonateHandler | None = None,
    impersonate_account: AdminImpersonateAccount | None = None,
    count_strategy: AdminCountStrategy = EXACT,
)

Bases: Generic[ModelT]

Declarative admin configuration for one SQLAlchemy model.

Instantiate once per managed model and pass it to :meth:AdminSite.register. Unlike Django's class-based ModelAdmin, this is a plain typed instance — the constructor signature is the contract, fields accept real SQLAlchemy column attributes (so typos surface in the editor, not at runtime), and there is no metaclass magic::

site.register(AdminModel(
    model=UserModel,
    list_display=[UserModel.email, UserModel.is_admin],
    search_fields=[UserModel.email],
    ordering=desc(UserModel.created_at),
))

Parameters:

Name Type Description Default
model type[ModelT]

The SQLAlchemy model class.

required
list_display Sequence[FieldRef] | None

Columns shown in the list view. None defaults to every column except the password hash.

None
list_filter Sequence[FieldRef]

Fields surfaced as filter dropdowns; matched via the repository's standard filter pipeline.

()
search_fields Sequence[FieldRef]

Text columns the list's search box (?q=) and the export look in. Each word of the term is an escaped, case-insensitive ILIKE %word% ORed across these columns, and every word must match in some column; % and _ are literal. The first entry also labels the row in FK selects and autocomplete.

()
readonly_fields Sequence[FieldRef]

Fields locked in the detail view.

()
ordering OrderRef | None

Default ordering. Accepts a column (ascending), desc(column) / asc(column), or a string column name with an optional leading - for descending. None falls back to created_at descending.

None
page_size int

Default rows per page in the list view.

25
identity_field FieldRef

Column used to look up a single row from the detail URL. Defaults to "id" (UUID PK).

'id'
repository_class type[BaseRepository[Any]] | None

Concrete repository. None synthesizes an anonymous repository bound to :attr:model.

None
verbose_name str | None

Singular display name; defaults to the model name humanized.

None
verbose_name_plural str | None

Plural display name; defaults to verbose_name pluralized (Category -> Categories).

None
can_create bool

Whether the admin exposes the column create form + POST endpoint. None (default) means True, or False when create_handler is given.

None
create_handler AdminCreateHandler | None

A create flow driven by a schema and a service instead of the columns (an API key minted and shown once). "+ New" opens the schema's form. Mutually exclusive with can_create=True.

None
can_edit bool

Whether the admin exposes the edit form + POST endpoint. Default True.

True
can_delete bool

Whether the admin exposes the delete action. Default True.

True
can_toggle_active bool

Whether the list view offers the built-in "Activate" / "Deactivate" bulk actions (they also need can_edit). False hides them and refuses a forged submission — for tables where is_active carries no meaning, such as a payout ledger. Default True.

True
can_import bool

Whether the admin exposes a CSV import page (GET/POST {prefix}/m/{slug}/import) that bulk-creates rows from an uploaded CSV. Default False (opt-in); also requires can_create.

False
actions Sequence[AnyActionHandler]

Custom bulk actions — functions decorated with :func:~tempest_fastapi_sdk.admin.admin_action. Each appears in the list view's bulk-action dropdown alongside the built-in activate / deactivate / delete; an action_policy on :func:~tempest_fastapi_sdk.admin.make_admin_router decides, per action, who sees and runs it.

()
upload_fields Sequence[FieldRef]

String columns rendered as file inputs in the create/edit form. The uploaded file is saved through upload_storage and the returned storage key is written to the column.

()
upload_storage UploadStorage | None

Backend used to persist uploaded files (LocalUploadStorage / MinIOUploadStorage). Required when upload_fields is non-empty.

None
upload_accept Mapping[FieldRef, Sequence[str]] | None

MIME types an upload field takes ({"receipt_key": ["application/pdf"]}). The input gets accept=, and a submission is refused with a field error unless the declared type is listed and, when the list holds any type :func:~tempest_fastapi_sdk.sniff_mime recognises (:data:~tempest_fastapi_sdk.utils.SNIFFABLE_MIMETYPES), the leading bytes sniff as a listed type — a PNG renamed .pdf is refused. The check is per list, not per type: mixing text/plain with application/pdf refuses plain text, since text has no signature to sniff. A field left out accepts anything, as before.

None
validate_edit EditValidator | None

Called on an edit submission with the stored row and the posted form, before any upload is written; a non-empty {field: message} refuses the save with those errors. For a rule that depends on the row's state, such as a receipt that cannot change once the row is final.

None
readonly_fields_for ReadonlyFieldsFor | None

Called with the stored row when its edit form is rendered and when it is submitted; the columns it returns are locked for that row on top of readonly_fields, the same way: left out of the edit form, and a value posted for them is ignored on save. For a column editable only while the row is in some state, such as a reason that freezes once the row is final. It covers the columns the form parses — upload and password fields are handled apart, so lock those with validate_edit — and the row's own edit form, not an inline formset.

None
audit_model type[BaseAuditLogModel] | None

When set, the detail view renders a per-row change timeline read from this audit table (matched on entity = the model name and entity_id = the row id). Pair it with BaseRepository(audit_model=...) + add_audited / update_audited / delete_audited so the history is actually written. None (default) shows only the created_by / updated_by stamps.

None
choices Mapping[FieldRef, ChoiceSource]

Columns rendered as a <select> of fixed values although the column itself is a plain String — an enum stored as text, or an open vocabulary the admin should still restrict. Each value is an Enum class (its values, labelled from the member names), a sequence of strings, or of (value, label) pairs. The form shows the select and the submission is refused with a field error when the value is not in the list. A column that is also in list_filter gets the same select (with the same labels) as its list filter instead of a free-text box. A real enum column (Mapped[MyEnum]) is a select already and needs no entry.

None
autocomplete_fields Sequence[FieldRef]

Foreign-key columns rendered as a typed search box (HTMX) instead of a <select> of every related row — removing the 1000-row cap and the plain-UUID fallback for large target tables. The target table must have its own registered AdminModel (its search_fields drive the search).

()
inlines Sequence[Inline]

Related child models listed on this model's detail view (Django TabularInline analog). Each :class:Inline shows the child rows pointing back via its fk_field plus links to the child admin and an "Add" link that pre-fills the parent foreign key.

()
lenses Sequence[Lens]

Named saved list-view presets (Nova-style lenses) rendered as tabs above the list; each applies its filters + ordering via ?lens=<slug>.

()
display_timezone str | None

IANA name of the timezone the operator reads and types datetimes in (for example "America/Sao_Paulo"). None — the default — keeps every datetime in UTC, which is what the columns store.

Set it and the panel becomes a real widget instead of a raw column editor: the list, the detail view and the edit form render each datetime converted to that zone, and a value typed into the form is read as wall-clock there and stored back in UTC. Without it a TIMESTAMP(timezone=True) column round-trips through an <input type="datetime-local"> that carries no offset at all, so an operator in Brazil types the local hour and the row keeps it as if it were UTC — three hours off, with nothing in the page saying which zone the box meant.

Only the human-facing views convert. The CSV/JSON export keeps UTC on purpose: it feeds machines, and a timestamp that silently changes meaning between the screen and the file is worse than one that always means the same thing.

None
password_fields Sequence[FieldRef]

Columns that take a plaintext password in the form and store its hash.

()
password_policy PasswordPolicy | None

Policy the plaintext must pass. None uses :class:PasswordPolicy defaults.

None
exclude_fields Sequence[FieldRef]

Columns the panel never shows or accepts — for a credential that is not a password, like a push subscription's endpoint / p256dh / auth, a device push_token or a totp_secret.

readonly_fields does not cover that case: it locks the input and still prints the value in the detail view. An excluded column leaves every surface at once — list, detail, create/edit form, CSV import, CSV/JSON export, sortable headers, the parent's inline table and the audit timeline's before/after rows — through :meth:hidden_field_names.

Hiding the timeline's rows is not enough on its own: the audit table itself would still hold the value. With audit_model set, every excluded column must also be listed in the model's __audit_redact__, which makes the audit write :data:~tempest_fastapi_sdk.db.audit.AUDIT_REDACTED in its place — construction raises otherwise.

Checked at construction, so a contradiction fails at import time instead of rendering the secret anyway: a name that is not a column, or one that another option also names (list_display, list_filter, search_fields, readonly_fields, upload_fields, autocomplete_fields, password_fields, identity_field, ordering, a lens's filters or order_by), raises ValueError. So does excluding a NOT NULL column with no default while can_create is on: the form could never fill it, and every create would end in Conflict creating <Model>.

()
row_scope AdminRowScope | None

Called with the signed-in principal and this admin on every request that reads or writes a row of :attr:model; the clause it returns is ANDed into every such query — list, count, export, detail, edit, delete, bulk and custom actions, autocomplete and foreign-key options where this model is the target, inlines where it is the child, upload downloads and the CSV import. Return sqlalchemy.true() to leave the rows unrestricted; any value that is not a SQLAlchemy clause — None included — raises :class:AdminRowScopeError (fail closed). A row outside the clause answers 404, the same as a row that does not exist, so the response never confirms it is there. A row the principal creates, edits or imports must still match the clause after the write, or the write is rolled back and refused. For a support role that sees only its own company's rows::

def own_company(user: UserModel, admin: AdminModel[Any]) -> Any:
    if user.is_superuser:
        return true()
    if user.company_id is None:
        return false()
    return TicketModel.company_id == user.company_id
None
m2m_fields Sequence[FieldRef]

Many-to-many relationships (relationship(..., secondary=...)) edited on the create/edit form as a multi-select of the target model's rows. The options are the rows the principal reaches through the target admin's row_scope (and need VIEW on it; without it the field is left out and the stored links are kept). Saving replaces the whole set in the same transaction as the row; a link the operator cannot see is kept, and an id outside the options is refused with the "does not exist" error. The detail view lists the linked rows. Checked at construction: a name that is not a relationship with secondary raises ValueError.

()
related_counts Sequence[RelatedCount]

Columns of the list view counting the child rows that reference each row (:class:RelatedCount), one GROUP BY query per page.

()
can_duplicate bool

Show a "Duplicate" button on the detail view that opens the create form filled with the row's values, minus the identity, unique columns, password and upload fields and the audit columns (created_at, updated_at, created_by, updated_by). Needs the column create form (can_create, no create_handler) and CREATE; the source row must be in the principal's scope. The submission is an ordinary create.

False
bulk_edit_fields Sequence[FieldRef]

Columns the list's selection can set on every checked row at once ("Edit field"). The value is typed into the column's own widget and validated like the edit form; it is written with one UPDATE ... WHERE id IN (...) AND <scope> in a transaction that is rolled back when the value takes any row out of the scope. A foreign key is checked against the target's scope, and with audit_model one audit entry is written per row. Needs can_edit and EDIT. Each name must be an editable column that is not an upload, password or many-to-many field.

()
impersonate AdminImpersonateHandler | None

Turns a row of this model into a "log in as" target. The detail view gains a button that opens a confirmation page; confirming resolves the account (impersonate_account), records the attempt, calls impersonate(operator, account) (sync or async) and redirects the browser to the URL it returns. Needs AdminPermissionEnum.IMPERSONATE, which make_admin_router never grants without an access_policy; with one, whatever the policy answers for it decides — a deny-list policy ("all but DELETE") grants it too. The row must be inside row_scope. The impersonation is refused when the row or the resolved account is an admin account (:meth:~tempest_fastapi_sdk.admin.AdminAuthBackend.is_admin_account), or when the account's id loads as an admin principal through the backend (a 1:1 profile sharing its primary key with an admin user). Each impersonation is logged at INFO (operator, model, row — never the URL) and, with audit_model set, written there as an event entry before the handler runs. See :func:~tempest_fastapi_sdk.admin.make_jwt_impersonation_handler.

None
impersonate_account AdminImpersonateAccount | None

Maps the row to the account the handler enters as (lambda profile: profile.user), sync or async; None (default) is the row itself. The admin-account refusal runs on what it returns, and the handler receives it as its second argument. Returning None answers 404.

None
count_strategy AdminCountStrategy

How the list counts its rows: "exact" (default), "estimate" or "none". See :class:AdminCountStrategyEnum. The dashboard card of the model follows the same strategy.

EXACT

Raises:

Type Description
TypeError

When model is not a subclass of :class:BaseModel, or when a field reference cannot be resolved to a column key.

ValueError

When display_timezone is not a zone the host's tz database knows, or when list_filter, search_fields or a lens' filters carries a key the repository would refuse with UnknownFilterKeyException (unknown column or operator), or when create_handler is combined with can_create=True, or when count_strategy is not an :class:AdminCountStrategyEnum value.

Build and validate the configuration. See class docstring.

creates property

creates: bool

Whether the list shows "+ New": the column form or a handler.

Returns:

Name Type Description
bool bool

True when :attr:can_create or :attr:create_handler

bool

is set.

get_lens

get_lens(slug: str) -> Lens | None

Return the registered lens whose slug matches, or None.

Parameters:

Name Type Description Default
slug str

The ?lens= value.

required

Returns:

Type Description
Lens | None

Lens | None: The matching lens.

scope_for async

scope_for(principal: object) -> ColumnElement[bool] | None

Resolve :attr:row_scope for principal.

Parameters:

Name Type Description Default
principal object

The signed-in admin principal.

required

Returns:

Type Description
ColumnElement[bool] | None

ColumnElement[bool] | None: The clause the principal's rows must

ColumnElement[bool] | None

match, or None when the admin declares no row_scope.

Raises:

Type Description
AdminRowScopeError

When the scope returns (or awaits to) anything that is not a SQLAlchemy clause, None included; logged with the model name before it propagates.

get_verbose_name

get_verbose_name() -> str

Return the configured (or auto-derived) singular display name.

Returns:

Name Type Description
str str

The display name.

get_verbose_name_plural

get_verbose_name_plural() -> str

Return the configured (or auto-derived) plural display name.

Returns:

Name Type Description
str str

The plural display name.

get_slug

get_slug() -> str

Return the URL slug under which the model is exposed.

The model's :meth:~tempest_fastapi_sdk.BaseModel.get_table_name, so admin URLs and DB tables stay in sync.

Returns:

Name Type Description
str str

The slug.

column_names

column_names() -> list[str]

Return every mapped column name on :attr:model.

Returns:

Type Description
list[str]

list[str]: Column keys in declaration order.

hidden_field_names

hidden_field_names() -> set[str]

Return the columns no read surface of the panel may show.

hashed_password, every credential column the model declares in __secret_columns__ (the SDK's own MFAMixin.totp_secret, the push subscription and device-token keys, the refresh-token and recovery-code digests — see :meth:~tempest_fastapi_sdk.db.model.BaseModel.get_secret_columns), every password_fields column and every exclude_fields column. The list, the export, the detail view, the sortable headers, a parent's inline table and the audit timeline all filter through this one set, so hiding a column is one decision and not one per template.

Returns:

Type Description
set[str]

set[str]: The hidden column names.

resolved_list_display

resolved_list_display() -> list[str]

Return the effective list_display column list.

Defaults to every column except :meth:hidden_field_names when unconfigured. A column named in password_fields is dropped even from an explicit list_display — this list also feeds the CSV/JSON export, and a digest has no business in either.

Returns:

Type Description
list[str]

list[str]: The list of columns to render.

readonly_field_names_for

readonly_field_names_for(instance: ModelT) -> set[str]

Return the columns locked on one row's edit form.

Parameters:

Name Type Description Default
instance ModelT

The stored row.

required

Returns:

Type Description
set[str]

set[str]: readonly_fields plus what readonly_fields_for

set[str]

returns for instance.

editable_field_names

editable_field_names(
    *, creating: bool = False, instance: ModelT | None = None
) -> list[str]

Return the columns a create/edit form should expose.

Excludes the primary key, the audit timestamps (created_at / updated_at), the password hash, the model's __secret_columns__, and any column listed in readonly_fields or exclude_fields — none of which a user edits directly through the generic admin form.

A secret column that is NOT NULL with no default comes back when creating: the create form starts blank, so it shows no stored value, and without the input no row of a model like BaseWebPushSubscriptionModel could be created through the panel. The edit form, the inline formset and every read surface still leave it out, since those would print the stored value.

A column named in password_fields is the exception: it comes back in, rendered as a password box that takes plaintext and is hashed on save. Without it no BaseUserModel subclass could be created through the panel at all — the form omitted the column, the insert hit the NOT NULL and the operator read Conflict creating <Model>.

Parameters:

Name Type Description Default
creating bool

Whether the form is the create form, which takes the required secret columns as blank inputs.

False
instance Any | None

The row being edited; when given, the columns readonly_fields_for locks for it are left out too (:meth:readonly_field_names_for).

None

Returns:

Type Description
list[str]

list[str]: Editable column keys in declaration order.

insertable_secret_names

insertable_secret_names() -> set[str]

Return the secret columns the create form must still accept.

The __secret_columns__ that are NOT NULL with neither a default nor a server default and that exclude_fields does not already remove: an insert without them could only fail. They are write-only — rendered blank on the create form and never read back by any surface.

Returns:

Type Description
set[str]

set[str]: The required secret column names.

build_repository

build_repository(session: AsyncSession) -> BaseRepository[ModelT]

Instantiate the repository for session.

Uses :attr:repository_class when provided (typically a subclass adding custom queries), otherwise instantiates :class:BaseRepository directly with model=self.model.

Parameters:

Name Type Description Default
session AsyncSession

The DB session to bind.

required

Returns:

Type Description
BaseRepository[ModelT]

BaseRepository[ModelT]: A repository ready to use.

custom_actions

custom_actions() -> list[AdminAction]

Return the registered custom actions in declaration order.

Returns:

Type Description
list[AdminAction]

list[AdminAction]: The actions passed via actions= ([]

list[AdminAction]

when none were registered).

get_action

get_action(name: str) -> AdminAction | None

Return the custom action named name, or None.

Parameters:

Name Type Description Default
name str

The action identifier (its submitted form value).

required

Returns:

Type Description
AdminAction | None

AdminAction | None: The matching action, or None when no

AdminAction | None

custom action with that name is registered.

ChoiceSource module-attribute

ChoiceSource = type[Enum] | Sequence[str | tuple[str, str]]

The fixed values of a choices field: an Enum class, or a sequence of strings or (value, label) pairs.

EditValidator module-attribute

EditValidator = Callable[[Any, Mapping[str, Any]], Mapping[str, str]]

(row, posted_form) -> {field: message}; empty accepts the edit.

ReadonlyFieldsFor module-attribute

ReadonlyFieldsFor = Callable[[Any], Sequence[FieldRef]]

(row) -> fields: the columns locked on this row's edit form, on top of readonly_fields.

AdminRowScope module-attribute

AdminRowScope = Callable[
    [Any, "AdminModel[Any]"], "ColumnElement[bool] | Awaitable[ColumnElement[bool]]"
]

(principal, admin) -> condition: the rows of admin.model the signed-in principal may reach, as a SQLAlchemy boolean clause. Every row is sqlalchemy.true(), said explicitly; None (a forgotten return) is refused with :class:AdminRowScopeError. Sync or async.

AdminRowScopeError

Bases: RuntimeError

A row_scope returned something that is not a SQLAlchemy clause.

Raised instead of treating the value as "every row": a scope function that forgets its return hands back None, and reading that as unrestricted would open every tenant's rows. The request fails with a 500 and the error is logged with the model name.

AdminCountStrategyEnum

Bases: BaseStrEnum

How the list view counts the rows behind its pagination.

EXACT runs COUNT(*) on every page, as the list always did. ESTIMATE reads PostgreSQL's planner statistic (pg_class.reltuples) instead, but only while the list shows the whole table: with a search, a filter, a lens or a row_scope clause other than true(), the statistic describes rows the operator is not looking at, so the count is exact again. Other dialects, and a table PostgreSQL never analyzed (reltuples = -1), count exactly too. NONE counts nothing: the list shows only previous / next.

AdminCountStrategy module-attribute

AdminCountStrategy = AdminCountStrategyEnum | Literal['exact', 'estimate', 'none']

What AdminModel(count_strategy=...) takes: the enum or its value.

AdminImpersonateHandler module-attribute

AdminImpersonateHandler = Callable[[Any, Any], 'str | Awaitable[str]']

(operator, account) -> url: where the browser goes to act as account.

operator is the signed-in admin principal and account what AdminModel(impersonate_account=...) resolved from the row (the row itself by default) — the identity the admin already checked is not an admin account. Sync or async. A handler that enters as anything other than account bypasses that check and must refuse admin accounts itself. The URL usually carries a credential, so the admin never logs it.

AdminImpersonateAccount module-attribute

AdminImpersonateAccount = Callable[[Any], 'Any | Awaitable[Any]']

(row) -> account: the account a row of the model logs in as.

For impersonate= on a profile model, lambda profile: profile.user. A sync resolver runs inside AsyncSession.run_sync, so it may read a lazy relationship; an async one must load what it reads itself (eager loading, AsyncAttrs.awaitable_attrs). None, an account without id, or one outside the row_scope of its own registered admin answers 404.

make_jwt_impersonation_handler

make_jwt_impersonation_handler(
    jwt: JWTUtils, *, redirect_url: str, ttl: timedelta = ADMIN_IMPERSONATION_TTL
) -> AdminImpersonateHandler

Build an impersonation handler that signs a short access token.

The token carries sub (the id of the account the admin resolved and checked — see AdminModel(impersonate_account=...)), typ set to :data:~tempest_fastapi_sdk.ACCESS_TOKEN_TYPE — so :func:~tempest_fastapi_sdk.make_bearer_token_dependency and :func:~tempest_fastapi_sdk.make_jwt_user_dependency accept it like any access token signed with the same secret — the target's email when it has one, and act = {"sub": <operator id>}, the RFC 8693 actor claim, so the app can tell an impersonated session from the user's own and log the operator behind each request (:func:~tempest_fastapi_sdk.token_actor reads it back, so a sensitive route can refuse an impersonated session). iat / exp come from :meth:JWTUtils.encode with ttl. The token is otherwise an ordinary access token: every route that accepts the user's own token accepts it.

Parameters:

Name Type Description Default
jwt JWTUtils

The helper the app verifies its access tokens with.

required
redirect_url str

Where the browser lands, with :data:IMPERSONATION_TOKEN_PLACEHOLDER ({token}) where the token goes, e.g. "https://app.example.com/impersonate#token={token}". A fragment (#) keeps the token out of the app server's access log and out of the Referer the landing page sends.

required
ttl timedelta

Token lifetime; defaults to :data:ADMIN_IMPERSONATION_TTL (15 minutes).

ADMIN_IMPERSONATION_TTL

Returns:

Name Type Description
AdminImpersonateHandler AdminImpersonateHandler

The handler to pass as

AdminImpersonateHandler

AdminModel(impersonate=...).

Raises:

Type Description
ValueError

When redirect_url has no {token} placeholder, or ttl is not positive.

ADMIN_IMPERSONATION_TTL module-attribute

ADMIN_IMPERSONATION_TTL: Final[timedelta] = timedelta(minutes=15)

Default lifetime of the token :func:make_jwt_impersonation_handler signs.

ADMIN_IMPERSONATION_EVENT module-attribute

ADMIN_IMPERSONATION_EVENT: Final[str] = 'admin.impersonate'

Event name of the audit entry an impersonation writes.

Stored in the event column when the audit table mixes in :class:~tempest_fastapi_sdk.db.audit.AuditRequestMixin, and under context["event"] otherwise.

ADMIN_IMPERSONATION_FAILED_EVENT module-attribute

ADMIN_IMPERSONATION_FAILED_EVENT: Final[str] = 'admin.impersonate.failed'

Event name of the entry written when the handler fails after the attempt.

The attempt (:data:ADMIN_IMPERSONATION_EVENT) is recorded before the handler runs; this second entry, with the reason in context["reason"], says no credential was handed over.

IMPERSONATION_TOKEN_PLACEHOLDER module-attribute

IMPERSONATION_TOKEN_PLACEHOLDER: Final[str] = '{token}'

Marker :func:make_jwt_impersonation_handler replaces with the token.

AdminLocale module-attribute

AdminLocale = Literal['en', 'pt-BR']

A language the admin catalog ships.

ADMIN_LOCALES module-attribute

ADMIN_LOCALES: Final[tuple[AdminLocale, ...]] = ('en', 'pt-BR')

Every locale in :data:ADMIN_MESSAGES, the default first.

DEFAULT_ADMIN_LOCALE module-attribute

DEFAULT_ADMIN_LOCALE: Final[AdminLocale] = 'en'

Locale of an AdminSite built without locale=.

ADMIN_MESSAGES module-attribute

ADMIN_MESSAGES: Final[Mapping[str, Mapping[str, str]]] = {
    "en": {
        "action.rows_selected.one": "{count} row(s) selected.",
        "action.rows_selected.other": "{count} row(s) selected.",
        "autocomplete.empty": "No matches",
        "bulk_edit.apply": "Apply to selected",
        "bulk_edit.done.one": "Set {field} on {count} row.",
        "bulk_edit.done.other": "Set {field} on {count} rows.",
        "bulk_edit.error.conflict": "The database refused that {field}; no row was changed.",
        "bulk_edit.error.locked.one": "{count} selected row locks this field.",
        "bulk_edit.error.locked.other": "{count} selected rows lock this field.",
        "bulk_edit.field": "Field",
        "bulk_edit.next": "Next",
        "bulk_edit.title": "Edit field",
        "card.level.green": "OK",
        "card.level.red": "Critical",
        "card.level.yellow": "Attention",
        "card.vs_before": "vs {previous} before",
        "common.delete": "Delete",
        "common.done": "Done",
        "common.download": "Download",
        "common.edit": "Edit",
        "common.filter": "Filter",
        "common.next": "Next",
        "common.no": "No",
        "common.page_of": "Page {page} of {pages}",
        "common.pagination": "Pagination",
        "common.prev": "Prev",
        "common.search": "Search",
        "common.search_placeholder": "Search…",
        "common.view": "View",
        "common.yes": "Yes",
        "dashboard.activity": "Recent activity",
        "dashboard.activity_empty": "No recorded changes yet.",
        "dashboard.activity_gone": "record no longer exists",
        "dashboard.browse": "Browse",
        "dashboard.business_metrics": "Business metrics",
        "dashboard.cpu": "CPU",
        "dashboard.disk": "Disk",
        "dashboard.empty.lead": "No models registered. Register an",
        "dashboard.empty.middle": "on the",
        "dashboard.empty.tail": "to populate this dashboard.",
        "dashboard.memory": "Memory",
        "dashboard.memory_usage": "{used} / {total} GB",
        "dashboard.new": "+ New",
        "dashboard.system_metrics": "System metrics",
        "detail.audit": "Audit",
        "detail.created_at": "Created at",
        "detail.created_by": "Created by",
        "detail.delete_confirm": "Delete this record? This cannot be undone.",
        "detail.duplicate": "Duplicate",
        "detail.history": "History",
        "detail.history.after": "after",
        "detail.history.before": "before",
        "detail.history.create": "create",
        "detail.history.delete": "delete",
        "detail.history.field": "field",
        "detail.history.update": "update",
        "detail.history_empty": "No recorded changes for this record.",
        "detail.inline_add": "Add",
        "detail.inline_editing_first": "Editing the first {shown} of {total}.",
        "detail.inline_empty": "No related records.",
        "detail.inline_error": "Some inline rows could not be saved.",
        "detail.inline_save": "Save {label}",
        "detail.inline_showing_first": "Showing the first {shown} of {total}.",
        "detail.updated_at": "Updated at",
        "detail.updated_by": "Updated by",
        "error.edit_conflict": "Someone else saved this record after you opened it. Nothing was saved: your values are below — review them and save again to overwrite.",
        "error.out_of_scope_committed": "The create handler saved this record by itself, and it falls outside the rows you may manage. It could not be undone; ask an administrator to review it.",
        "error.out_of_scope": "This record would fall outside the rows you may manage; nothing was saved.",
        "export.error.xlsx_extra": 'Exporting .xlsx needs the spreadsheet extra: pip install "{extra}"',
        "filter.shortcut.last_30_days": "30 days",
        "filter.shortcut.last_7_days": "7 days",
        "filter.shortcut.last_month": "Last month",
        "filter.shortcut.this_month": "This month",
        "filter.shortcut.today": "Today",
        "flash.already_submitted": "This form was already submitted; it did not run again.",
        "form.back": "Back",
        "form.cancel": "Cancel",
        "form.create": "Create",
        "form.error.choice": "Choose one of the listed values for {label}.",
        "form.error.fk_missing": "Select a valid choice; that record does not exist.",
        "form.error.invalid": "Invalid value for {label}.",
        "form.error.json": "Invalid JSON for {label}.",
        "form.error.required": "This field is required.",
        "form.error.upload_type": "Only {types} files are accepted.",
        "form.file_current": "Current: {value} — choose a file to replace.",
        "form.json_hint": "JSON — must parse (e.g.",
        "form.multiselect_empty": "No records to choose from.",
        "form.multiselect_hint": "Hold Ctrl (Cmd on a Mac) to select more than one.",
        "form.none": "— none —",
        "form.password_keep": "Leave blank to keep the current password.",
        "form.required": "required",
        "form.save": "Save",
        "form.timezone_hint": "Timezone: {zone} — stored as UTC.",
        "form.title.create": "New {model}",
        "form.title.duplicate": "Duplicate {model}",
        "form.title.edit": "Edit {model}",
        "import.back": "Back to list",
        "import.column.errors": "Errors",
        "import.column.row": "Row",
        "import.confirm.one": "Confirm import of {count} record",
        "import.confirm.other": "Confirm import of {count} records",
        "import.confirm_blocked": "Nothing is imported while any row has an error: fix the file and preview it again.",
        "import.created.one": "Created {count} record(s).",
        "import.created.other": "Created {count} record(s).",
        "import.error.conflict": "This row conflicts with a stored record (a duplicate value or a missing reference).",
        "import.error.not_committed": "Nothing was imported: some rows were refused when the import ran. The table changed since the preview; review the errors below.",
        "import.error.payload": "This preview expired or belongs to another import. Upload the file again.",
        "import.error.too_large": "The file is larger than {max_kib} KiB. Split it and import each part.",
        "import.error.unreadable": "Could not read the file as UTF-8 CSV.",
        "import.error.unreadable_xlsx": "Could not read the file as an .xlsx workbook.",
        "import.error.xlsx_extra": 'Importing .xlsx needs the spreadsheet extra: pip install "{extra}"',
        "import.error.xlsx_formula": "{cells}: formula with no calculated value. Open the file in a spreadsheet app, save it and upload it again.",
        "import.error.xlsx_too_large": "The workbook passes the import limits ({max_rows} rows, {max_mib} MiB uncompressed). Split it and import each part.",
        "import.expected_columns": "Expected header columns:",
        "import.file": "CSV file",
        "import.file_any": "CSV or XLSX file",
        "import.header_rule": "The first row must be the header; each following row becomes one record. Up to {max_kib} KiB.",
        "import.nothing_to_import": "The file has no rows to import.",
        "import.preview.accepted.one": "{count} of {total} row(s) will be imported.",
        "import.preview.accepted.other": "{count} of {total} row(s) will be imported.",
        "import.preview.refused.one": "{count} row refused:",
        "import.preview.refused.other": "{count} rows refused:",
        "import.preview.sample.one": "Preview of the first row",
        "import.preview.sample.other": "Preview of the first {count} rows",
        "import.preview_again": "Preview another file",
        "import.preview_submit": "Preview",
        "import.title": "Import {models}",
        "import.xlsx_rule": "An .xlsx file is read from its first sheet.",
        "list.actions": "Actions",
        "list.activate": "Activate",
        "list.any": "— any —",
        "list.apply": "Apply",
        "list.apply_selected": "Apply to selected",
        "list.bulk_action": "Bulk action",
        "list.bulk_confirm": "Apply the selected action to the checked rows?",
        "list.bulk_confirm_dangerous": 'Run "{label}" on the checked rows? This cannot be undone.',
        "list.bulk_edit": "Edit field",
        "list.clear_filter": "Clear filter",
        "list.date_from": "{label} from",
        "list.date_to": "{label} to",
        "list.deactivate": "Deactivate",
        "list.empty": "No records.",
        "list.export_csv": "Export CSV",
        "list.export_json": "Export JSON",
        "list.export_xlsx": "Export XLSX",
        "list.filtered_by": "Filtered by {field}: {value}",
        "list.import_csv": "Import CSV",
        "list.lens_all": "All",
        "list.lenses": "Lenses",
        "list.new": "New {model}",
        "list.records.one": "{count} record",
        "list.records.other": "{count} records",
        "list.select_all": "Select all",
        "list.select_row": "Select row",
        "login.email": "Email",
        "login.error.csrf": "The sign-in form expired, please try again",
        "login.error.throttled": "Too many failed logins, try again later",
        "login.password": "Password",
        "login.sign_in": "Sign in",
        "logs.col.level": "Level",
        "logs.col.logger": "Logger",
        "logs.col.message": "Message",
        "logs.col.timestamp": "Timestamp",
        "logs.empty_filter": "No records match the current filter.",
        "logs.export_json": "Export .json",
        "logs.export_md": "Export .md",
        "logs.export_note": "An export covers every record matching the current filter, newest first, up to {max} — not just this page. Markdown wraps each traceback in a fenced block so it survives a paste into an issue; JSON ships the records verbatim.",
        "logs.heading": "Application logs",
        "logs.no_files.lead": "No log files found. File logging is written by",
        "logs.no_files.tail": "; once it runs, records show up here.",
        "logs.page_of_total": "Page {page} of {pages} ({total} records)",
        "logs.read_at": "Read at",
        "logs.refresh": "Refresh",
        "logs.refresh_title": "Reload the newest records with the current filter",
        "logs.search": "Search message",
        "logs.search_placeholder": "substring…",
        "logs.source": "Source",
        "logs.source_all": "all",
        "logs.traceback": "Traceback",
        "map.cities": "Cities",
        "map.city": "City",
        "map.empty": "No {value_label} with a location yet.",
        "map.failed": "This map could not be counted. The error is in the server log.",
        "map.legend_city": "city (area = {value_label})",
        "map.legend_title": "{value_label} per state",
        "map.located": "With location",
        "map.located_detail": "{states} state(s), {cities} city(ies) shown",
        "map.state": "State",
        "map.states": "States",
        "map.total": "Total",
        "map.unlocated": "No location",
        "metrics.failed": "These indicators could not be collected. The error is in the server log.",
        "mfa.code": "Authentication code",
        "mfa.error.invalid": "Invalid code",
        "mfa.error.throttled": "Too many invalid codes, try again later",
        "mfa.heading": "Two-factor authentication",
        "mfa.lead": "Enter the 6-digit code from your authenticator app.",
        "mfa.title": "Two-factor",
        "mfa.verify": "Verify",
        "nav.dashboard": "Dashboard",
        "nav.label": "Admin navigation",
        "nav.logout": "Logout",
        "nav.logs": "Logs",
        "nav.maps": "Maps",
        "nav.metrics": "Metrics",
        "nav.models": "Models",
        "nav.sql": "SQL console",
        "nav.storage": "Storage",
        "nav.system": "System",
        "nav.tasks": "Tasks",
        "nav.toggle": "Toggle navigation",
        "nav.view_site": "View site",
        "secrets.copy.one": "Copy this value now: it is shown only on this page.",
        "secrets.copy.other": "Copy these values now: they are shown only on this page.",
        "secrets.reload_runs": "Reloading runs the action again.",
        "secrets.reload_safe.one": "Reloading will not show it again.",
        "secrets.reload_safe.other": "Reloading will not show them again.",
        "site.index_subtitle": "Site administration",
        "sql.affected.one": "Statement executed. {count} row affected.",
        "sql.affected.other": "Statement executed. {count} rows affected.",
        "sql.allowed": "Allowed:",
        "sql.denied": "Denied:",
        "sql.empty": "The query returned no rows.",
        "sql.error.denied": "Refused by policy",
        "sql.error.failed": "Statement failed",
        "sql.nothing": "nothing",
        "sql.null": "NULL",
        "sql.placeholder": "SELECT * FROM ...",
        "sql.row_cap": "Row cap:",
        "sql.rows.one": "{count} row",
        "sql.rows.other": "{count} rows",
        "sql.run": "Run",
        "sql.seconds": "{value}s",
        "sql.statement": "Statement",
        "sql.tables": "Tables:",
        "sql.truncated": "truncated at {max} rows",
        "sql.warning": "This console can modify data. Statements run against the live database and are not undoable from here.",
        "storage.back": "Back to storage",
        "storage.back_root": "Back to the root",
        "storage.bytes": "{count} bytes",
        "storage.col.modified": "Modified",
        "storage.col.name": "Name",
        "storage.col.size": "Size",
        "storage.col.type": "Type",
        "storage.content": "Content",
        "storage.delete_confirm": "Delete this file? This cannot be undone.",
        "storage.empty": "The bucket is empty.",
        "storage.fact.etag": "ETag",
        "storage.fact.key": "Key",
        "storage.file": "File",
        "storage.flash.deleted": "Deleted {key}.",
        "storage.flash.moved": "Moved {key} to {target}.",
        "storage.flash.replaced": "Replaced {key}.",
        "storage.flash.saved": "Saved {key}.",
        "storage.flash.uploaded": "Uploaded {key}.",
        "storage.folder": "Folder",
        "storage.folder_kind": "folder",
        "storage.items.one": "{count} item",
        "storage.items.other": "{count} items",
        "storage.name_placeholder": "keep the file's name",
        "storage.no_preview.lead": "No preview for",
        "storage.no_preview.tail": ". Download it to open.",
        "storage.not_found": "Object not found",
        "storage.nothing_under": "Nothing under",
        "storage.object": "Object",
        "storage.open": "Open",
        "storage.overwrite": "Overwrite",
        "storage.read_only": "Read-only",
        "storage.rename": "Rename",
        "storage.rename_to": "Rename or move to",
        "storage.replace": "Replace",
        "storage.replace_content": "Replace content",
        "storage.save_as": "Save as",
        "storage.save_as_folders": "creates folders",
        "storage.save_as_optional": "optional;",
        "storage.save_hint": "Saving is refused if the file changed since this page loaded.",
        "storage.too_large": "Too large to preview here (over {size}). Download it to read.",
        "storage.upload": "Upload",
        "storage.upload_limit": "Up to {size} per file, into",
        "tasks.all": "All",
        "tasks.attempts_of": "{attempts} of {max}",
        "tasks.back": "Back to tasks",
        "tasks.cancel": "Cancel this run",
        "tasks.cancel_hint": "Cancelling is cooperative: the row flips now, and the worker stops at its next progress check.",
        "tasks.col.attempts": "Attempts",
        "tasks.col.finished": "Finished",
        "tasks.col.kind": "Kind",
        "tasks.col.progress": "Progress",
        "tasks.col.requested": "Requested",
        "tasks.col.result": "Result",
        "tasks.col.retries": "Retries",
        "tasks.col.stage": "Stage",
        "tasks.col.started": "Started",
        "tasks.col.status": "Status",
        "tasks.col.task": "Task",
        "tasks.default": "default",
        "tasks.error": "Error",
        "tasks.every": "every {seconds}s",
        "tasks.no_runs.lead": "No runs recorded yet. Rows appear here once a",
        "tasks.no_runs.tail": "enqueues work.",
        "tasks.no_schedule": "No tasks registered on the broker.",
        "tasks.off": "off",
        "tasks.on_demand": "on demand",
        "tasks.once_at": "once at {at}",
        "tasks.percent": "{value} percent",
        "tasks.run": "Run",
        "tasks.run_gone": "This run is no longer stored. Retention sweeps delete finished rows, so a bookmarked link outlives the record it points at.",
        "tasks.run_not_found": "Run not found",
        "tasks.runs": "Runs",
        "tasks.schedule": "Schedule",
        "tasks.scope": "This panel shows what is declared on the broker and what was persisted by the workers. It does not show live queue depth — TaskIQ exposes none.",
        "tasks.up_to": "up to {max}",
        "common.page": "Page {page}",
        "common.page_of_estimated": "Page {page} of ~{pages}",
        "dashboard.count_estimated": "~{count}",
        "detail.history.impersonate": "logged in as",
        "detail.history.impersonate_failed": "log in as failed",
        "detail.history.restore": "Restore",
        "detail.history.restore_hint": "Open the edit form with the values this change replaced",
        "impersonate.button": "Log in as",
        "impersonate.confirm": "Log in as this user",
        "impersonate.lead": "You are about to enter the application as {model} {target}. Everything you do there acts as this account.",
        "impersonate.recorded": "This access is recorded with your name and the time.",
        "impersonate.refused_admin": "This account can sign into the admin itself; logging in as it is not allowed.",
        "impersonate.title": "Log in as user",
        "list.records_estimated.one": "~{count} record",
        "list.records_estimated.other": "~{count} records",
        "list.records_estimated_hint": "Estimated from the database statistics; search or filter for an exact count.",
        "restore.intro": "Values from before the change of {at} are filled in: {fields}. Review them and save to restore; nothing changes until you save.",
        "search.empty": "Nothing matches “{query}”.",
        "search.for": "Results for “{query}”",
        "search.label": "Search every model",
        "search.open_list": "Open list",
        "search.placeholder": "Search everything…",
        "search.prompt": "Type a term to search every model.",
        "search.see_all": "See all",
        "search.title": "Search",
        "search.too_long": "The search term is too long: up to {max_length} characters and {max_terms} words.",
    },
    "pt-BR": {
        "action.rows_selected.one": "{count} linha selecionada.",
        "action.rows_selected.other": "{count} linhas selecionadas.",
        "autocomplete.empty": "Nenhum resultado",
        "bulk_edit.apply": "Aplicar às selecionadas",
        "bulk_edit.done.one": "{field} alterado em {count} linha.",
        "bulk_edit.done.other": "{field} alterado em {count} linhas.",
        "bulk_edit.error.conflict": "O banco recusou esse valor de {field}; nenhuma linha foi alterada.",
        "bulk_edit.error.locked.one": "{count} linha selecionada trava este campo.",
        "bulk_edit.error.locked.other": "{count} linhas selecionadas travam este campo.",
        "bulk_edit.field": "Campo",
        "bulk_edit.next": "Continuar",
        "bulk_edit.title": "Editar campo",
        "card.level.green": "OK",
        "card.level.red": "Crítico",
        "card.level.yellow": "Atenção",
        "card.vs_before": "contra {previous} antes",
        "common.delete": "Excluir",
        "common.done": "Concluir",
        "common.download": "Baixar",
        "common.edit": "Editar",
        "common.filter": "Filtrar",
        "common.next": "Próxima",
        "common.no": "Não",
        "common.page_of": "Página {page} de {pages}",
        "common.pagination": "Paginação",
        "common.prev": "Anterior",
        "common.search": "Buscar",
        "common.search_placeholder": "Buscar…",
        "common.view": "Ver",
        "common.yes": "Sim",
        "dashboard.activity": "Atividade recente",
        "dashboard.activity_empty": "Nenhuma alteração registrada ainda.",
        "dashboard.activity_gone": "registro não existe mais",
        "dashboard.browse": "Abrir",
        "dashboard.business_metrics": "Indicadores do negócio",
        "dashboard.cpu": "CPU",
        "dashboard.disk": "Disco",
        "dashboard.empty.lead": "Nenhum modelo registrado. Registre um",
        "dashboard.empty.middle": "no",
        "dashboard.empty.tail": "para preencher este painel.",
        "dashboard.memory": "Memória",
        "dashboard.memory_usage": "{used} / {total} GB",
        "dashboard.new": "+ Novo",
        "dashboard.system_metrics": "Métricas do sistema",
        "detail.audit": "Auditoria",
        "detail.created_at": "Criado em",
        "detail.created_by": "Criado por",
        "detail.delete_confirm": "Excluir este registro? Isso não pode ser desfeito.",
        "detail.duplicate": "Duplicar",
        "detail.history": "Histórico",
        "detail.history.after": "depois",
        "detail.history.before": "antes",
        "detail.history.create": "criação",
        "detail.history.delete": "exclusão",
        "detail.history.field": "campo",
        "detail.history.update": "alteração",
        "detail.history_empty": "Nenhuma alteração registrada para este registro.",
        "detail.inline_add": "Adicionar",
        "detail.inline_editing_first": "Editando os primeiros {shown} de {total}.",
        "detail.inline_empty": "Nenhum registro relacionado.",
        "detail.inline_error": "Algumas linhas não puderam ser salvas.",
        "detail.inline_save": "Salvar {label}",
        "detail.inline_showing_first": "Mostrando os primeiros {shown} de {total}.",
        "detail.updated_at": "Atualizado em",
        "detail.updated_by": "Atualizado por",
        "error.edit_conflict": "Outra pessoa salvou este registro depois que você o abriu. Nada foi salvo: seus valores estão abaixo — revise e salve de novo para sobrescrever.",
        "error.out_of_scope_committed": "O handler de criação salvou este registro sozinho, e ele fica fora das linhas que você pode gerenciar. Não foi possível desfazer; peça a um administrador para revisar.",
        "error.out_of_scope": "Este registro ficaria fora das linhas que você pode gerenciar; nada foi salvo.",
        "export.error.xlsx_extra": 'Exportar .xlsx precisa do extra de planilha: pip install "{extra}"',
        "filter.shortcut.last_30_days": "30 dias",
        "filter.shortcut.last_7_days": "7 dias",
        "filter.shortcut.last_month": "Mês passado",
        "filter.shortcut.this_month": "Este mês",
        "filter.shortcut.today": "Hoje",
        "flash.already_submitted": "Este formulário já foi enviado; ele não rodou de novo.",
        "form.back": "Voltar",
        "form.cancel": "Cancelar",
        "form.create": "Criar",
        "form.error.choice": "Escolha um dos valores listados para {label}.",
        "form.error.fk_missing": "Escolha uma opção válida; esse registro não existe.",
        "form.error.invalid": "Valor inválido para {label}.",
        "form.error.json": "JSON inválido para {label}.",
        "form.error.required": "Este campo é obrigatório.",
        "form.error.upload_type": "Só são aceitos arquivos {types}.",
        "form.file_current": "Atual: {value} — escolha um arquivo para substituir.",
        "form.json_hint": "JSON — precisa ser válido (ex.:",
        "form.multiselect_empty": "Nenhum registro para escolher.",
        "form.multiselect_hint": "Segure Ctrl (Cmd no Mac) para escolher mais de um.",
        "form.none": "— nenhum —",
        "form.password_keep": "Deixe em branco para manter a senha atual.",
        "form.required": "obrigatório",
        "form.save": "Salvar",
        "form.timezone_hint": "Fuso horário: {zone} — gravado em UTC.",
        "form.title.create": "Novo: {model}",
        "form.title.duplicate": "Duplicar: {model}",
        "form.title.edit": "Editar: {model}",
        "import.back": "Voltar para a lista",
        "import.column.errors": "Erros",
        "import.column.row": "Linha",
        "import.confirm.one": "Confirmar a importação de {count} registro",
        "import.confirm.other": "Confirmar a importação de {count} registros",
        "import.confirm_blocked": "Nada é importado enquanto alguma linha tiver erro: corrija o arquivo e gere a prévia de novo.",
        "import.created.one": "{count} registro criado.",
        "import.created.other": "{count} registros criados.",
        "import.error.conflict": "Esta linha conflita com um registro gravado (valor duplicado ou referência inexistente).",
        "import.error.not_committed": "Nada foi importado: algumas linhas foram recusadas na hora da importação. A tabela mudou desde a prévia; veja os erros abaixo.",
        "import.error.payload": "Esta prévia expirou ou pertence a outra importação. Envie o arquivo de novo.",
        "import.error.too_large": "O arquivo passa de {max_kib} KiB. Divida-o e importe cada parte.",
        "import.error.unreadable": "Não foi possível ler o arquivo como CSV em UTF-8.",
        "import.error.unreadable_xlsx": "Não foi possível ler o arquivo como planilha .xlsx.",
        "import.error.xlsx_extra": 'Importar .xlsx precisa do extra de planilha: pip install "{extra}"',
        "import.error.xlsx_formula": "{cells}: fórmula sem valor calculado. Abra o arquivo no Excel (ou LibreOffice), salve e envie de novo.",
        "import.error.xlsx_too_large": "A planilha passa dos limites do import ({max_rows} linhas, {max_mib} MiB descompactada). Divida e importe cada parte.",
        "import.expected_columns": "Colunas esperadas no cabeçalho:",
        "import.file": "Arquivo CSV",
        "import.file_any": "Arquivo CSV ou XLSX",
        "import.header_rule": "A primeira linha precisa ser o cabeçalho; cada linha seguinte vira um registro. Até {max_kib} KiB.",
        "import.nothing_to_import": "O arquivo não tem linhas para importar.",
        "import.preview.accepted.one": "{count} de {total} linha(s) será importada.",
        "import.preview.accepted.other": "{count} de {total} linhas serão importadas.",
        "import.preview.refused.one": "{count} linha recusada:",
        "import.preview.refused.other": "{count} linhas recusadas:",
        "import.preview.sample.one": "Prévia da primeira linha",
        "import.preview.sample.other": "Prévia das primeiras {count} linhas",
        "import.preview_again": "Gerar prévia de outro arquivo",
        "import.preview_submit": "Gerar prévia",
        "import.title": "Importar {models}",
        "import.xlsx_rule": "Um arquivo .xlsx é lido da primeira aba.",
        "list.actions": "Ações",
        "list.activate": "Ativar",
        "list.any": "— qualquer —",
        "list.apply": "Aplicar",
        "list.apply_selected": "Aplicar aos selecionados",
        "list.bulk_action": "Ação em lote",
        "list.bulk_confirm": "Aplicar a ação escolhida às linhas marcadas?",
        "list.bulk_confirm_dangerous": 'Executar "{label}" nas linhas marcadas? Isso não pode ser desfeito.',
        "list.bulk_edit": "Editar campo",
        "list.clear_filter": "Limpar filtro",
        "list.date_from": "{label} desde",
        "list.date_to": "{label} até",
        "list.deactivate": "Desativar",
        "list.empty": "Nenhum registro.",
        "list.export_csv": "Exportar CSV",
        "list.export_json": "Exportar JSON",
        "list.export_xlsx": "Exportar XLSX",
        "list.filtered_by": "Filtrado por {field}: {value}",
        "list.import_csv": "Importar CSV",
        "list.lens_all": "Todos",
        "list.lenses": "Visões",
        "list.new": "Novo: {model}",
        "list.records.one": "{count} registro",
        "list.records.other": "{count} registros",
        "list.select_all": "Selecionar todos",
        "list.select_row": "Selecionar linha",
        "login.email": "E-mail",
        "login.error.csrf": "O formulário de login expirou; tente de novo",
        "login.error.throttled": "Muitas tentativas de login falharam; tente mais tarde",
        "login.password": "Senha",
        "login.sign_in": "Entrar",
        "logs.col.level": "Nível",
        "logs.col.logger": "Logger",
        "logs.col.message": "Mensagem",
        "logs.col.timestamp": "Data e hora",
        "logs.empty_filter": "Nenhum registro atende ao filtro atual.",
        "logs.export_json": "Exportar .json",
        "logs.export_md": "Exportar .md",
        "logs.export_note": "A exportação cobre todo registro que atende ao filtro atual, do mais novo para o mais antigo, até {max} — não só esta página. O Markdown põe cada traceback num bloco cercado, para sobreviver a uma colagem numa issue; o JSON leva os registros como estão.",
        "logs.heading": "Logs da aplicação",
        "logs.no_files.lead": "Nenhum arquivo de log encontrado. O log em arquivo é escrito por",
        "logs.no_files.tail": "; quando ele rodar, os registros aparecem aqui.",
        "logs.page_of_total": "Página {page} de {pages} ({total} registros)",
        "logs.read_at": "Lido em",
        "logs.refresh": "Atualizar",
        "logs.refresh_title": "Recarregar os registros mais novos com o filtro atual",
        "logs.search": "Buscar na mensagem",
        "logs.search_placeholder": "trecho…",
        "logs.source": "Origem",
        "logs.source_all": "todos",
        "logs.traceback": "Traceback",
        "map.cities": "Cidades",
        "map.city": "Cidade",
        "map.empty": "Nenhum(a) {value_label} com localização ainda.",
        "map.failed": "Não foi possível contar este mapa. O erro está no log do servidor.",
        "map.legend_city": "cidade (área = {value_label})",
        "map.legend_title": "{value_label} por estado",
        "map.located": "Com localização",
        "map.located_detail": "{states} estado(s), {cities} cidade(s) no mapa",
        "map.state": "Estado",
        "map.states": "Estados",
        "map.total": "Total",
        "map.unlocated": "Sem localização",
        "metrics.failed": "Não foi possível coletar estes indicadores. O erro está no log do servidor.",
        "mfa.code": "Código de autenticação",
        "mfa.error.invalid": "Código inválido",
        "mfa.error.throttled": "Muitos códigos inválidos; tente mais tarde",
        "mfa.heading": "Autenticação em dois fatores",
        "mfa.lead": "Digite o código de 6 dígitos do seu app autenticador.",
        "mfa.title": "Dois fatores",
        "mfa.verify": "Verificar",
        "nav.dashboard": "Painel",
        "nav.label": "Navegação do admin",
        "nav.logout": "Sair",
        "nav.logs": "Logs",
        "nav.maps": "Mapas",
        "nav.metrics": "Indicadores",
        "nav.models": "Modelos",
        "nav.sql": "Console SQL",
        "nav.storage": "Arquivos",
        "nav.system": "Sistema",
        "nav.tasks": "Tarefas",
        "nav.toggle": "Abrir ou fechar a navegação",
        "nav.view_site": "Ver site",
        "secrets.copy.one": "Copie este valor agora: ele só aparece nesta página.",
        "secrets.copy.other": "Copie estes valores agora: eles só aparecem nesta página.",
        "secrets.reload_runs": "Recarregar executa a ação de novo.",
        "secrets.reload_safe.one": "Recarregar não o mostra de novo.",
        "secrets.reload_safe.other": "Recarregar não os mostra de novo.",
        "site.index_subtitle": "Administração do site",
        "sql.affected.one": "Comando executado. {count} linha afetada.",
        "sql.affected.other": "Comando executado. {count} linhas afetadas.",
        "sql.allowed": "Permitido:",
        "sql.denied": "Negadas:",
        "sql.empty": "A consulta não devolveu linhas.",
        "sql.error.denied": "Recusado pela política",
        "sql.error.failed": "O comando falhou",
        "sql.nothing": "nada",
        "sql.null": "NULL",
        "sql.placeholder": "SELECT * FROM ...",
        "sql.row_cap": "Limite de linhas:",
        "sql.rows.one": "{count} linha",
        "sql.rows.other": "{count} linhas",
        "sql.run": "Executar",
        "sql.seconds": "{value}s",
        "sql.statement": "Comando",
        "sql.tables": "Tabelas:",
        "sql.truncated": "cortado em {max} linhas",
        "sql.warning": "Este console pode alterar dados. Os comandos rodam no banco de produção e não podem ser desfeitos daqui.",
        "storage.back": "Voltar para os arquivos",
        "storage.back_root": "Voltar para a raiz",
        "storage.bytes": "{count} bytes",
        "storage.col.modified": "Modificado",
        "storage.col.name": "Nome",
        "storage.col.size": "Tamanho",
        "storage.col.type": "Tipo",
        "storage.content": "Conteúdo",
        "storage.delete_confirm": "Excluir este arquivo? Isso não pode ser desfeito.",
        "storage.empty": "O bucket está vazio.",
        "storage.fact.etag": "ETag",
        "storage.fact.key": "Chave",
        "storage.file": "Arquivo",
        "storage.flash.deleted": "{key} excluído.",
        "storage.flash.moved": "{key} movido para {target}.",
        "storage.flash.replaced": "{key} substituído.",
        "storage.flash.saved": "{key} salvo.",
        "storage.flash.uploaded": "{key} enviado.",
        "storage.folder": "Pasta",
        "storage.folder_kind": "pasta",
        "storage.items.one": "{count} item",
        "storage.items.other": "{count} itens",
        "storage.name_placeholder": "manter o nome do arquivo",
        "storage.no_preview.lead": "Sem prévia para",
        "storage.no_preview.tail": ". Baixe para abrir.",
        "storage.not_found": "Objeto não encontrado",
        "storage.nothing_under": "Nada em",
        "storage.object": "Objeto",
        "storage.open": "Abrir",
        "storage.overwrite": "Sobrescrever",
        "storage.read_only": "Somente leitura",
        "storage.rename": "Renomear",
        "storage.rename_to": "Renomear ou mover para",
        "storage.replace": "Substituir",
        "storage.replace_content": "Substituir o conteúdo",
        "storage.save_as": "Salvar como",
        "storage.save_as_folders": "cria pastas",
        "storage.save_as_optional": "opcional;",
        "storage.save_hint": "O salvamento é recusado se o arquivo mudou desde que esta página abriu.",
        "storage.too_large": "Grande demais para a prévia aqui (mais de {size}). Baixe para ler.",
        "storage.upload": "Enviar",
        "storage.upload_limit": "Até {size} por arquivo, em",
        "tasks.all": "Todos",
        "tasks.attempts_of": "{attempts} de {max}",
        "tasks.back": "Voltar para as tarefas",
        "tasks.cancel": "Cancelar esta execução",
        "tasks.cancel_hint": "O cancelamento é cooperativo: a linha muda agora, e o worker para na próxima checagem de progresso.",
        "tasks.col.attempts": "Tentativas",
        "tasks.col.finished": "Terminou",
        "tasks.col.kind": "Tipo",
        "tasks.col.progress": "Progresso",
        "tasks.col.requested": "Pedida em",
        "tasks.col.result": "Resultado",
        "tasks.col.retries": "Novas tentativas",
        "tasks.col.stage": "Etapa",
        "tasks.col.started": "Começou",
        "tasks.col.status": "Status",
        "tasks.col.task": "Tarefa",
        "tasks.default": "o padrão",
        "tasks.error": "Erro",
        "tasks.every": "a cada {seconds}s",
        "tasks.no_runs.lead": "Nenhuma execução registrada ainda. As linhas aparecem quando um",
        "tasks.no_runs.tail": "enfileira trabalho.",
        "tasks.no_schedule": "Nenhuma tarefa registrada no broker.",
        "tasks.off": "desligadas",
        "tasks.on_demand": "sob demanda",
        "tasks.once_at": "uma vez em {at}",
        "tasks.percent": "{value} por cento",
        "tasks.run": "Execução",
        "tasks.run_gone": "Esta execução não está mais gravada. A limpeza por retenção apaga as linhas terminadas, então um link salvo dura mais que o registro.",
        "tasks.run_not_found": "Execução não encontrada",
        "tasks.runs": "Execuções",
        "tasks.schedule": "Agenda",
        "tasks.scope": "Este painel mostra o que está declarado no broker e o que os workers gravaram. Ele não mostra a profundidade da fila ao vivo — o TaskIQ não expõe isso.",
        "tasks.up_to": "até {max}",
        "common.page": "Página {page}",
        "common.page_of_estimated": "Página {page} de ~{pages}",
        "dashboard.count_estimated": "~{count}",
        "detail.history.impersonate": "entrou como",
        "detail.history.impersonate_failed": "falha ao entrar como",
        "detail.history.restore": "Restaurar",
        "detail.history.restore_hint": "Abre o form de edição com os valores que esta mudança substituiu",
        "impersonate.button": "Entrar como",
        "impersonate.confirm": "Entrar como este usuário",
        "impersonate.lead": "Você vai entrar na aplicação como {model} {target}. Tudo o que fizer lá age como esta conta.",
        "impersonate.recorded": "Este acesso fica registrado com o seu nome e o horário.",
        "impersonate.refused_admin": "Esta conta entra no próprio admin; entrar como ela não é permitido.",
        "impersonate.title": "Entrar como usuário",
        "list.records_estimated.one": "~{count} registro",
        "list.records_estimated.other": "~{count} registros",
        "list.records_estimated_hint": "Estimativa da estatística do banco; busque ou filtre para a contagem exata.",
        "restore.intro": "Os valores de antes da mudança de {at} estão preenchidos: {fields}. Revise e salve para restaurar; nada muda até você salvar.",
        "search.empty": "Nada encontrado para “{query}”.",
        "search.for": "Resultados para “{query}”",
        "search.label": "Buscar em todos os models",
        "search.open_list": "Abrir listagem",
        "search.placeholder": "Buscar em tudo…",
        "search.prompt": "Digite um termo para buscar em todos os models.",
        "search.see_all": "Ver todos",
        "search.title": "Busca",
        "search.too_long": "O termo de busca é longo demais: até {max_length} caracteres e {max_terms} palavras.",
    },
}

{locale: {key: template}}; templates use str.format placeholders.

admin_text

admin_text(locale: str, key: str, /, **params: Any) -> str

Return the catalog text for key in locale.

A key missing from locale falls back to English, and one missing from both to the key itself, so a gap renders something readable instead of failing the page; tests/test_admin_i18n_guard.py keeps both languages complete, so neither fallback is reached by the SDK's own keys.

Parameters:

Name Type Description Default
locale str

One of :data:ADMIN_LOCALES.

required
key str

The catalog key, such as "list.apply".

required
**params Any

Values for the template's {placeholders}.

{}

Returns:

Name Type Description
str str

The formatted text.

admin_plural

admin_plural(locale: str, key: str, count: int, /, **params: Any) -> str

Return the singular or plural catalog text for count.

Reads <key>.one when count is 1 and <key>.other otherwise — the rule both shipped languages follow — and passes count to the template along with params.

Parameters:

Name Type Description Default
locale str

One of :data:ADMIN_LOCALES.

required
key str

The catalog key without the .one / .other suffix.

required
count int

The number the text describes.

required
**params Any

Further {placeholder} values.

{}

Returns:

Name Type Description
str str

The formatted text.

ADMIN_IMPORT_MAX_BYTES module-attribute

ADMIN_IMPORT_MAX_BYTES: Final[int] = 512 * 1024

Largest CSV, in bytes, the import page accepts.

The preview carries the whole file to the confirmation as one signed hidden field, so the cap also bounds that request. Measured over six files of 512 KiB (random hex, random printable ASCII, random Latin-1, random CJK, random emoji, one-character lines), the signed field came to at most 571 099 bytes — random printable ASCII, which compresses least — under the 1 MiB Starlette allows one multipart field (max_part_size).

ADMIN_IMPORT_PREVIEW_MAX_AGE_SECONDS module-attribute

ADMIN_IMPORT_PREVIEW_MAX_AGE_SECONDS: Final[int] = 3600

How long a preview can be confirmed before the file must be sent again.

ADMIN_IMPORT_PREVIEW_ROWS module-attribute

ADMIN_IMPORT_PREVIEW_ROWS: Final[int] = 20

Rows of the file shown in the preview table; the counts cover all of them.

Inline

Inline(
    model: type[BaseModel],
    fk_field: FieldRef,
    *,
    list_display: Sequence[FieldRef] | None = None,
    label: str | None = None,
    editable: bool = False,
    can_delete: bool = False,
)

A related child model surfaced on the parent's detail view.

Django's TabularInline analog: the detail view of the parent lists the child rows that point back at it (via fk_field) as a compact table, with a link to each child's own admin and an "Add" link that pre-fills the parent foreign key. The child model must have its own registered :class:AdminModel for the links to work (the inline reuses the child admin's list_display and CRUD routes); without it, the rows still render read-only.

When editable is set, the same rows render as an in-place formset (one row of inputs per child, plus one blank row to add another) posting back to the parent's detail view — no navigation to the child admin. Editing an inline requires the child model to have its own registered :class:AdminModel (the formset reuses its editable fields, minus upload/autocomplete columns, which stay on the child's own form) and that admin's can_edit; can_delete adds a per-row delete checkbox (gated on the child admin's can_delete).

Attributes:

Name Type Description
model type[BaseModel]

The child model class.

fk_field str

The child column that references the parent.

list_display list[str] | None

Columns to show; falls back to the child admin's list_display (or every column).

label str | None

Section heading; defaults to the model name.

editable bool

Render the rows as an editable in-place formset.

can_delete bool

Show a per-row delete checkbox (editable only).

Build the inline config. See class docstring.

Parameters:

Name Type Description Default
model type[BaseModel]

The child model class.

required
fk_field FieldRef

The child column referencing the parent.

required
list_display Sequence[FieldRef] | None

Columns to show.

None
label str | None

Section heading.

None
editable bool

Render an in-place editable formset instead of a read-only table.

False
can_delete bool

Add a per-row delete checkbox (only when editable and the child admin allows deletion).

False

Raises:

Type Description
TypeError

When model is not a BaseModel subclass.

get_slug

get_slug() -> str

Return the child model's admin slug (its table name).

Returns:

Name Type Description
str str

The table name used to look the child admin up.

get_label

get_label() -> str

Return the section heading for this inline.

Returns:

Name Type Description
str str

The configured label, or a name derived from the model.

Lens

Lens(
    name: str,
    *,
    filters: dict[str, Any] | None = None,
    order_by: str | None = None,
    label: str | None = None,
)

A named, saved list-view preset (Nova-style lens).

A lens bundles a set of filters and an optional ordering under a label. On the list view lenses render as tabs; clicking one applies its filters (ANDed with the user's search/filters) and ordering. A "support triage" lens might pin {"status": "open", "priority__gte": 3} sorted by oldest-first, so an operator reaches the working set in one click instead of re-entering filters.

Attributes:

Name Type Description
name str

The lens identifier; its slug (lowercased, spaces→hyphens) is the ?lens= value.

filters dict[str, Any]

Column name to the value the tab's rows must match, ANDed into the query, e.g. {"user_id": 1234, "is_active": True}. A list is IN, None is IS NULL, and a <column>__<op> key applies an operator ({"price__gte": 10}); every convention is listed on :class:~tempest_fastapi_sdk.BaseRepository. An unknown column or operator makes :class:AdminModel raise ValueError at construction.

order_by str | None

Column to order by; -col for descending. Applied unless the user clicked a column sort.

label str | None

Tab label; defaults to name.

Build a lens. See class docstring.

Parameters:

Name Type Description Default
name str

The lens identifier.

required
filters dict[str, Any] | None

Column name to the value the tab's rows must match, ANDed together, e.g. {"user_id": 1234, "is_active": True}. A list is IN, None is IS NULL, and a <column>__<op> key applies an operator ({"price__gte": 10}); every convention is listed on :class:~tempest_fastapi_sdk.BaseRepository. An unknown column or operator makes :class:AdminModel raise ValueError at construction.

None
order_by str | None

Ordering column (-col = desc).

None
label str | None

Tab label.

None

slug

slug() -> str

Return the URL slug (?lens= value) for this lens.

Returns:

Name Type Description
str str

Lowercased name with non-alphanumeric runs hyphenated.

get_label

get_label() -> str

Return the tab label.

Returns:

Name Type Description
str str

The configured label, or the name.

RelatedCount

RelatedCount(fk: InstrumentedAttribute[Any], *, label: str | None = None)

A list-view column counting the child rows that point at each row.

Declared on the parent admin with the child's foreign-key column (RelatedCount(OrderModel.user_id, label="Orders") on the users admin). The list renders one extra column holding, per row, how many child rows reference it. The counts of a page come from one SELECT fk, COUNT(*) ... WHERE fk IN (<page ids>) GROUP BY fk, never one query per row, and that query carries the child admin's row_scope, so the number covers only the children the principal reaches.

When the child model has its own registered :class:AdminModel and the principal may VIEW it, the count links to the child's list filtered by the parent (?filter_<fk>=<id>). A child the principal may not VIEW drops the column altogether: the number is that model's data, whichever page shows it. A child with no registered admin is asked through a throwaway AdminModel(child), like an :class:Inline, and renders the count without a link.

Attributes:

Name Type Description
model type[BaseModel]

The child model, read from the column.

fk_field str

The child column that references the parent.

label str | None

Column heading; defaults to the child's plural name.

target_table str

The parent table the column references.

target_column str

The parent column it references (id).

Build the related count. See class docstring.

Parameters:

Name Type Description Default
fk InstrumentedAttribute[Any]

The child's foreign-key column, as a mapped attribute (OrderModel.user_id) so the child model is known.

required
label str | None

Column heading.

None

Raises:

Type Description
TypeError

When fk is not a mapped column attribute of a BaseModel subclass.

ValueError

When the column carries no ForeignKey.

get_slug

get_slug() -> str

Return the child model's admin slug (its table name).

Returns:

Name Type Description
str str

The table name used to look the child admin up.

key

key() -> str

Return the identifier of this count among the parent's counts.

Returns:

Name Type Description
str str

<child table>.<fk column>.

AdminPermissionEnum

Bases: BaseStrEnum

An admin action gated by an :data:AdminAccessPolicy.

IMPERSONATE (entering the app as a row of a model declared with AdminModel(impersonate=...)) is the one permission that is not granted when make_admin_router runs without an access_policy: acting as another account reaches past the admin's own screens. With a policy, whatever it answers for IMPERSONATE decides — a deny-list policy ("everything but DELETE") grants it as well.

AdminAccessPolicy module-attribute

AdminAccessPolicy = Callable[
    [Any, "AdminModel[Any]", AdminPermissionEnum], bool | Awaitable[bool]
]

AdminActionPolicy module-attribute

AdminActionPolicy = Callable[
    [Any, "AdminModel[Any]", "AdminAction"], bool | Awaitable[bool]
]

AdminSurfaceEnum

Bases: BaseStrEnum

An admin panel that is not about one model.

Gated by an :data:AdminSurfacePolicy instead of the per-model :data:AdminAccessPolicy, since there is no :class:AdminModel to ask about.

AdminSurfacePolicy module-attribute

AdminSurfacePolicy = Callable[[Any, AdminSurfaceEnum], bool | Awaitable[bool]]

MetricCard dataclass

MetricCard(label: str, compute: CardCompute, help_text: str | None = None)

A dashboard business-metric card.

Attributes:

Name Type Description
label str

The card heading.

compute CardCompute

Async function returning the card data — a :class:MetricValue, :class:MetricTrend or :class:MetricPartition.

help_text str | None

Optional sub-label shown under the value.

MetricValue dataclass

MetricValue(value: Any, unit: str | None = None)

A single headline number.

Attributes:

Name Type Description
value Any

The value to show (number or preformatted string).

unit str | None

Optional unit suffix ("orders", "BRL").

MetricTrend dataclass

MetricTrend(value: float, previous: float, unit: str | None = None)

A number compared against a previous period.

Attributes:

Name Type Description
value float

The current value.

previous float

The value for the comparison period.

unit str | None

Optional unit suffix.

delta property

delta: float

Return value - previous.

Returns:

Name Type Description
float float

The absolute change.

pct property

pct: float | None

Return the percentage change, or None when undefined.

Returns:

Type Description
float | None

float | None: delta / previous * 100; None when

float | None

previous is zero (no baseline).

direction property

direction: str

Return the trend direction.

Returns:

Name Type Description
str str

"up", "down" or "flat".

MetricPartition dataclass

MetricPartition(segments: list[tuple[str, float]] = list())

A breakdown of a total across labeled segments.

Attributes:

Name Type Description
segments list[tuple[str, float]]

(label, value) pairs.

total property

total: float

Return the sum of every segment value.

Returns:

Name Type Description
float float

The total across segments.

MetricsArea dataclass

MetricsArea(
    title: str,
    schema: type[BaseModel],
    provider: MetricsProvider,
    method: str,
    thresholds: Mapping[str, Threshold] = dict(),
    units: Mapping[str, str] = dict(),
)

A page of indicators, one card per field of schema.

Attributes:

Name Type Description
title str

The page heading and the sidebar label.

schema type[BaseModel]

The schema the method returns. Each field becomes a card: title is the label (the field name when unset), description the line under the value. A field typed :class:MetricValue, :class:MetricTrend or :class:MetricPartition renders as that card; a number renders as a value card.

provider MetricsProvider

Builds the service from the admin's database session.

method str

The service method that returns schema. Called with no arguments; sync or async.

thresholds Mapping[str, Threshold]

Field name → bands. Applies to a number or to the current value of a :class:MetricTrend.

units Mapping[str, str]

Field name → unit shown after a number ("BRL", "rides").

slug str

The URL segment, derived from title.

Raises:

Type Description
ValueError

When method is empty, or thresholds / units name a field schema does not have — a typo there would otherwise leave the card uncoloured in silence.

collect async

collect(session: AsyncSession) -> BaseModel

Build the service and call the method.

Parameters:

Name Type Description Default
session AsyncSession

The admin's database session.

required

Returns:

Name Type Description
BaseModel BaseModel

What the method returned.

Raises:

Type Description
TypeError

When the method returns something other than an instance of :attr:schema.

cards

cards(
    result: BaseModel,
) -> list[tuple[str, str | None, CardData, MetricLevelEnum | None]]

Turn the method's result into card data, in field order.

Parameters:

Name Type Description Default
result BaseModel

An instance of :attr:schema.

required

Returns:

Type Description
list[tuple[str, str | None, CardData, MetricLevelEnum | None]]

list[tuple[str, str | None, CardData, MetricLevelEnum | None]]:

list[tuple[str, str | None, CardData, MetricLevelEnum | None]]

(label, help, data, level) per field; level is None

list[tuple[str, str | None, CardData, MetricLevelEnum | None]]

for a field with no threshold or no numeric value.

MetricsProvider module-attribute

MetricsProvider = Callable[['AsyncSession'], Any]

Builds the service from the admin's database session.

The service class itself fits (RideMetricsService takes the session in its __init__), and so does a composition function (build_ride_metrics_service). Sync or async.

Threshold dataclass

Threshold(green: float, yellow: float, lower_is_better: bool = False)

Green / yellow / red bands for one numeric indicator.

With lower_is_better=False (the default) a value at or above green is green, at or above yellow is yellow, and below yellow is red. With lower_is_better=True the comparison flips: at or below green is green, at or below yellow is yellow, above yellow is red — "messages until the user found the route" is good when it is small. Both limits are inclusive on the better side.

Attributes:

Name Type Description
green float

The limit of the green band.

yellow float

The limit of the yellow band.

lower_is_better bool

Whether smaller values are healthier.

Raises:

Type Description
ValueError

When the limits are in the wrong order for the direction (green < yellow when higher is better, or green > yellow when lower is better), which would make the yellow band empty or inverted.

level

level(value: float) -> MetricLevelEnum

Return the band value falls in.

Parameters:

Name Type Description Default
value float

The indicator's current value.

required

Returns:

Name Type Description
MetricLevelEnum MetricLevelEnum

GREEN, YELLOW or RED.

MetricLevelEnum

Bases: BaseStrEnum

The band a numeric indicator falls in.

admin_action

admin_action(
    *,
    label: str,
    name: str | None = None,
    dangerous: bool = False,
    schema: type[BaseModel] | None = None,
) -> Callable[[_HandlerT], _HandlerT]

Mark an async function as a custom admin action.

The decorated function is registered by passing it to AdminModel(actions=[...]); the decorator only attaches metadata, so the function stays directly callable (and unit-testable) on its own.

The panel commits the request session after the handler returns, with or without secrets in the result, and rolls it back when the handler raises.

With schema, picking the action on the list opens a form generated from the model, with the selected ids carried along; the handler runs only on a valid submission, as handler(data, ctx). An invalid one re-renders the form with 400, and an :class:~tempest_fastapi_sdk.AppException from the handler rolls the session back and re-renders it with the message. The form carries a single-use nonce, so resubmitting the same form does not run the action again.

Parameters:

Name Type Description Default
label str

Dropdown label shown to the operator.

required
name str | None

Stable identifier (the submitted form value). Defaults to the function's __name__.

None
dangerous bool

Flag a destructive action for a stronger UI confirm.

False
schema type[BaseModel] | None

The input asked before the action runs (a reason, an amount, a date).

None

Returns:

Type Description
Callable[[_HandlerT], _HandlerT]

Callable[[_HandlerT], _HandlerT]: The decorator, returning the

Callable[[_HandlerT], _HandlerT]

function unchanged.

resolve_admin_action

resolve_admin_action(func: AnyActionHandler) -> AdminAction

Return the :class:AdminAction attached by :func:admin_action.

Parameters:

Name Type Description Default
func AnyActionHandler

A function passed to AdminModel(actions=).

required

Returns:

Name Type Description
AdminAction AdminAction

The attached metadata + handler.

Raises:

Type Description
TypeError

When func was not decorated with :func:admin_action.

ActionHandler module-attribute

ActionHandler = Callable[[AdminActionContext], Awaitable['AdminActionResult | None']]

An async (ctx) custom action: the selected rows and the session.

SchemaActionHandler module-attribute

SchemaActionHandler = Callable[
    [Any, AdminActionContext], Awaitable["AdminActionResult | None"]
]

An async (data, ctx) custom action declared with schema=.

data is an instance of the action's schema, validated from the form the operator filled in after picking the action.

AnyActionHandler module-attribute

AnyActionHandler = ActionHandler | SchemaActionHandler

Either kind of custom action, as AdminModel(actions=...) takes them.

AdminActionContext dataclass

AdminActionContext(
    ids: list[Any],
    repository: BaseRepository[Any],
    db_session: AsyncSession,
    request: Request,
    session: AdminSession,
    principal: Any,
)

Everything a custom action handler needs to do its work.

Attributes:

Name Type Description
ids list[Any]

Identity values of the rows the user selected.

repository BaseRepository[Any]

Repository bound to the request DB session for this admin's model.

db_session AsyncSession

The request DB session (for work beyond the repository).

request Request

The inbound request.

session AdminSession

The authenticated admin session.

principal Any

The resolved admin user row.

AdminActionResult dataclass

AdminActionResult(
    message: str, category: str = "success", secrets: Sequence[AdminSecret] = ()
)

The outcome of a custom action.

Without secrets the message is flashed on the list view, carried by the redirect's query string. With secrets the panel answers the action's own POST with a page that shows the message and each secret once — no redirect, so no value reaches a URL, the browser history, an access log or a Referer — sent with Cache-Control: no-store and Referrer-Policy: no-referrer. The request's database session is committed before that page renders, so a secret on screen is never one whose row was rolled back.

Attributes:

Name Type Description
message str

Human-readable result shown to the operator.

category str

Banner style — "success" (default), "error" or "warning".

secrets Sequence[AdminSecret]

Values to reveal once. Any sequence is accepted (a list included) and stored as a tuple.

AdminSecret dataclass

AdminSecret(label: str, value: str)

A value the operator must see exactly once, such as a new API key.

The value is left out of repr so a logged or printed result does not carry it.

Attributes:

Name Type Description
label str

What the value is ("API key for ana@example.com").

value str

The secret itself, in plaintext.

AdminCreateHandler dataclass

AdminCreateHandler(
    schema: type[BaseModel], handler: CreateHandlerFunc, label: str | None = None
)

A create flow driven by a schema and a service, not by the columns.

Some rows are born from a service rather than typed in: an API key is a generated secret stored as a hash and shown in plaintext once, so the column form (key_hash, key_prefix typed by hand) is wrong for it. Pass this as AdminModel(create_handler=...) and the list's "+ New" button opens a form generated from :attr:schema; on submit the panel validates it and calls :attr:handler.

The handler returns the same :class:AdminActionResult a custom action does. With secrets, the database session is committed and the values are shown once on the POST's own response; reloading that page does not call the handler again (a single-use nonce in the form). Without them, the panel redirects to the list and flashes the message. An :class:~tempest_fastapi_sdk.AppException raised by the handler re-renders the form with its message and what was typed.

Attributes:

Name Type Description
schema type[BaseModel]

The Pydantic model the form is generated from and the submission is validated against. A field whose name is in the admin's autocomplete_fields renders as the same foreign-key search box.

handler CreateHandlerFunc

The async function that creates the record.

label str | None

Text of the "+ New" button and the form heading; None uses New <verbose name>.

CreateHandlerFunc module-attribute

CreateHandlerFunc = Callable[
    [Any, AdminActionContext], Awaitable["AdminActionResult | None"]
]

An async (data, ctx) creating a record from a validated schema.

data is an instance of the handler's schema; ctx is the same :class:AdminActionContext a custom action gets, with ids empty.

manual_payout_admin

manual_payout_admin(
    model: type[BaseManualPayoutModel],
    *,
    upload_storage: UploadStorage,
    ledger_factory: Callable[[AsyncSession], WalletLedger] | None = None,
    hooks: ManualPayoutHooks | None = None,
    audit_model: type[BaseAuditLogModel] | None = None,
    display_timezone: str | None = None,
    verbose_name: str = "Saque manual",
    verbose_name_plural: str = "Saques manuais",
    actions: Sequence[ActionHandler] = (),
) -> AdminModel[Any]

Configure the panel for a manual payout table.

  • list filtered by status (a select labelled Pendente / Pago / Cancelado / Recusado), searchable by correlation_id;
  • no "Activate" / "Deactivate" bulk actions, and is_active read-only: a payout is never switched off;
  • every money column read-only — amount, user, key, correlation id, status, end-to-end id and who completed or refused it; no create, no delete, no import;
  • receipt_key an upload that takes only a PDF (declared type application/pdf and bytes starting %PDF-), downloadable from the row's page, and refused once the row is no longer PENDING;
  • rejection_reason editable while the row is PENDING; on a final row it leaves the edit form and a posted value is ignored (readonly_fields_for);
  • the "Marcar como pago" action (:func:make_mark_paid_action), and, with ledger_factory, "Recusar e devolver" (:func:make_reject_action).

Parameters:

Name Type Description Default
model type[BaseManualPayoutModel]

The project's concrete model.

required
upload_storage UploadStorage

Where receipts are stored.

required
ledger_factory Callable[[AsyncSession], WalletLedger] | None

Builds the wallet ledger on the panel's session. None leaves the "refuse and refund" action out.

None
hooks ManualPayoutHooks | None

Callbacks run inside each transition — the same instance the provider gets.

None
audit_model type[BaseAuditLogModel] | None

Shows the row's change timeline when set.

None
display_timezone str | None

IANA zone for the datetimes.

None
verbose_name str

Singular name in the panel.

'Saque manual'
verbose_name_plural str

Plural name in the panel.

'Saques manuais'
actions Sequence[ActionHandler]

More actions, after the preset's.

()

Returns:

Type Description
AdminModel[Any]

AdminModel[Any]: Ready for site.register.

make_mark_paid_action

make_mark_paid_action(
    model: type[BaseManualPayoutModel], *, hooks: ManualPayoutHooks | None = None
) -> ActionHandler

Build the "mark as paid" action for one concrete model.

Each selected row goes through :meth:~tempest_fastapi_sdk.wallet.ManualPayoutService.mark_paid with require_receipt=True, in its own transaction: a row without a receipt is left alone, a final row never changes, and two operators clicking at once complete the row once. A row whose on_paid hook raises is rolled back, logged and reported; the other rows still move.

Parameters:

Name Type Description Default
model type[BaseManualPayoutModel]

The project's concrete model. The action reads it from the panel's repository; the parameter keeps the factory's signature uniform with :func:make_reject_action.

required
hooks ManualPayoutHooks | None

Callbacks; on_paid runs here.

None

Returns:

Name Type Description
ActionHandler ActionHandler

The decorated action.

make_reject_action

make_reject_action(
    model: type[BaseManualPayoutModel],
    *,
    ledger_factory: Callable[[AsyncSession], WalletLedger],
    hooks: ManualPayoutHooks | None = None,
) -> ActionHandler

Build the "refuse and refund" action for one concrete model.

The operator writes the reason in the row's rejection_reason field first; the action then runs :meth:~tempest_fastapi_sdk.wallet.ManualPayoutService.reject per row, each in its own transaction: the row turns REJECTED, the amount goes back to the wallet as a WITHDRAW_REFUND line and on_rejected runs, in one commit. A row without a reason is left alone.

Parameters:

Name Type Description Default
model type[BaseManualPayoutModel]

The project's concrete model. The action reads it from the panel's repository.

required
ledger_factory Callable[[AsyncSession], WalletLedger]

Builds the wallet ledger on the panel's session — the refund and the status change must share it.

required
hooks ManualPayoutHooks | None

Callbacks; on_rejected runs here.

None

Returns:

Name Type Description
ActionHandler ActionHandler

The decorated action.

MARK_PAID_ACTION module-attribute

MARK_PAID_ACTION: Final[str] = 'mark_manual_payout_paid'

Name of the "mark as paid" action (the bulk form's value).

RECEIPT_CONTENT_TYPES module-attribute

RECEIPT_CONTENT_TYPES: Final[tuple[str, ...]] = ('application/pdf',)

What the receipt field takes: a PDF, checked by type and by %PDF-.

REJECT_ACTION module-attribute

REJECT_ACTION: Final[str] = 'reject_manual_payout'

Name of the "refuse and refund" action (the bulk form's value).

STATUS_LABELS module-attribute

STATUS_LABELS: Final[dict[str, str]] = {
    ManualPayoutStatusEnum.PENDING.value: "Pendente",
    ManualPayoutStatusEnum.COMPLETED.value: "Pago",
    ManualPayoutStatusEnum.CANCELED.value: "Cancelado",
    ManualPayoutStatusEnum.REJECTED.value: "Recusado",
}

Portuguese labels for the status filter, keyed by the stored value.

mercado_pago_simulation_actions

mercado_pago_simulation_actions(
    simulator: MercadoPagoSimulator,
    *,
    reference_field: str = "correlation_id",
    transitions: Sequence[MercadoPagoTransition] = DEFAULT_SIMULATION_TRANSITIONS,
    labels: Mapping[str, str] | None = None,
) -> list[ActionHandler]

Build one admin action per Mercado Pago move.

Hang the result on the AdminModel of the service's charge table (AdminModel(ChargeModel, actions=[*mercado_pago_simulation_actions(sim)])). Each action reads reference_field from every selected row and calls :meth:~tempest_fastapi_sdk.integrations.payment.adapters.MercadoPagoSimulator.apply with it, so the simulator must deliver on its own: build it with app= and webhook_url= (in process) or an absolute webhook_url. "Simular estorno" is marked dangerous.

Parameters:

Name Type Description Default
simulator MercadoPagoSimulator

Moves, signs and delivers. Its construction already refused anything but development and test.

required
reference_field str

The row attribute holding the order's external_reference — the reference the service sent on create — or the order id.

'correlation_id'
transitions Sequence[MercadoPagoTransition]

The moves to offer, in menu order.

DEFAULT_SIMULATION_TRANSITIONS
labels Mapping[str, str] | None

Menu labels by move, over :data:SIMULATION_ACTION_LABELS.

None

Returns:

Type Description
list[ActionHandler]

list[ActionHandler]: The actions, ready for AdminModel(actions=).

Raises:

Type Description
ValueError

When the simulator has no webhook_url, a move is repeated, or a move is unknown.

DANGEROUS_TRANSITIONS module-attribute

DANGEROUS_TRANSITIONS: Final[frozenset[str]] = frozenset({'refund'})

Moves the panel confirms with the destructive prompt.

DEFAULT_SIMULATION_TRANSITIONS module-attribute

DEFAULT_SIMULATION_TRANSITIONS: Final[tuple[MercadoPagoTransition, ...]] = (
    "pay",
    "expire",
    "refund",
)

The moves offered when the caller names none.

SIMULATION_ACTION_LABELS module-attribute

SIMULATION_ACTION_LABELS: Final[Mapping[str, str]] = {
    "pay": "Simular pagamento",
    "expire": "Simular expiração",
    "fail": "Simular falha",
    "cancel": "Simular cancelamento",
    "capture": "Simular captura",
    "refund": "Simular estorno",
}

Label of each move in the panel's action menu.

SIMULATION_ACTION_PREFIX module-attribute

SIMULATION_ACTION_PREFIX: Final[str] = 'simulate_mercado_pago_'

Prefix of each action's name; the move follows (simulate_mercado_pago_pay).

AdminAuthBackend

Bases: ABC, Generic[PrincipalT]

Abstract base for admin authentication.

Implementations receive a session-bound async DB session per login attempt; the default :class:UserModelAuthBackend queries a :class:BaseUserModel subclass and enforces is_admin=True. Custom backends can use the same protocol to integrate LDAP, OAuth, IAM tokens, etc.

The class is generic in the principal — the value authenticate returns and every other method consumes. Parameterizing it is what makes that contract checkable::

class LdapAuthBackend(AdminAuthBackend[LdapEntry]):
    def display_name(self, principal: LdapEntry) -> str:
        return principal.common_name

Subclassing without a parameter stays valid and resolves to AdminAuthBackend[Any], which is the behaviour that shipped before the class was generic — nothing has to change to keep working.

authenticate abstractmethod async

authenticate(session: AsyncSession, *, identifier: str, password: str) -> PrincipalT

Verify credentials and return the authenticated principal.

Parameters:

Name Type Description Default
session AsyncSession

A live DB session.

required
identifier str

The login identifier (typically email).

required
password str

The plaintext password.

required

Returns:

Name Type Description
PrincipalT PrincipalT

The authenticated principal. The admin router

calls PrincipalT

meth:principal_id on the return value to derive the

PrincipalT

session payload. Typically a :class:BaseUserModel row.

Raises:

Type Description
AdminAuthError

On any rejection (unknown user, wrong password, not an admin, disabled account).

load_principal abstractmethod async

load_principal(session: AsyncSession, principal_id: str) -> PrincipalT | None

Reload the principal from storage given its ID.

Called on every request once the session cookie has been validated. Returning None invalidates the session.

Parameters:

Name Type Description Default
session AsyncSession

A live DB session.

required
principal_id str

The identifier produced by :meth:principal_id at login.

required

Returns:

Type Description
PrincipalT | None

PrincipalT | None: The reloaded principal, or None when

PrincipalT | None

it no longer exists or no longer has admin access.

principal_id abstractmethod

principal_id(principal: PrincipalT) -> str

Return a stable identifier for the authenticated principal.

Parameters:

Name Type Description Default
principal PrincipalT

The value returned by :meth:authenticate.

required

Returns:

Name Type Description
str str

The identifier serialized into the session cookie.

display_name

display_name(principal: PrincipalT) -> str

Return a human-readable label for the principal.

Defaults to the principal's email attribute (or its repr when missing); override for richer labels.

Parameters:

Name Type Description Default
principal PrincipalT

The principal.

required

Returns:

Name Type Description
str str

A label suitable for the admin header bar.

is_admin_account

is_admin_account(target: object) -> bool

Whether target is an account that can itself use the admin.

The impersonation flow (AdminModel(impersonate=...)) refuses such a target: entering as another operator would turn one admin's grant into another's, and the audit trail would credit the wrong person. The default reads a truthy is_admin attribute, which is what :class:~tempest_fastapi_sdk.BaseUserModel carries; override it when admin access is decided by something else (a role column, a group).

Parameters:

Name Type Description Default
target object

The row the operator asked to enter as.

required

Returns:

Name Type Description
bool bool

True to refuse the impersonation.

load_account async

load_account(session: AsyncSession, account_id: str) -> PrincipalT | None

Load the account with account_id without any sign-in filter.

:meth:is_admin_identity asks :meth:is_admin_account about what this returns, so an admin that :meth:load_principal drops — inactive, revoked, missing MFA — is still recognised as an admin. The default returns None (the base class does not know where accounts live); a backend whose :meth:load_principal filters should override it. The account is the same kind of object the backend signs in, only without the sign-in filter.

Parameters:

Name Type Description Default
session AsyncSession

A live DB session.

required
account_id str

The account's id, as text.

required

Returns:

Type Description
PrincipalT | None

PrincipalT | None: The account, or None when unknown.

is_admin_identity async

is_admin_identity(session: AsyncSession, account_id: str) -> bool

Whether account_id names an account that can use the admin.

The impersonation flow asks this about the id that goes into the credential, on top of :meth:is_admin_account on the row, so a model whose rows share their primary key with the user table (a 1:1 profile) cannot hand out an admin's identity. The default answers True when :meth:load_principal finds a principal for that id, or when :meth:load_account returns an account :meth:is_admin_account calls an admin. A custom backend whose load_principal filters (inactive, MFA) must override :meth:load_account or this method, or such an admin passes.

Parameters:

Name Type Description Default
session AsyncSession

A live DB session.

required
account_id str

The account's id, as text.

required

Returns:

Name Type Description
bool bool

True to refuse the impersonation.

credential_fingerprint

credential_fingerprint(principal: PrincipalT) -> str | None

Return a value that changes whenever the principal's credential does.

The admin router stores a keyed digest of it in the session cookie at sign-in and compares it on every request, so changing the password (or whatever the fingerprint covers) ends every session issued before the change. Defaults to None: the session is not bound to any credential, which suits backends whose credential the SDK cannot see (LDAP, OAuth). Override to opt in.

Parameters:

Name Type Description Default
principal PrincipalT

The authenticated principal.

required

Returns:

Type Description
str | None

str | None: The fingerprint, or None to bind nothing.

mfa_enabled

mfa_enabled(principal: PrincipalT) -> bool

Whether principal must pass a TOTP challenge after login.

Defaults to False so non-user backends (LDAP, OAuth) skip the second factor unless they opt in. Override to gate the login behind MFA.

Parameters:

Name Type Description Default
principal PrincipalT

The authenticated principal.

required

Returns:

Name Type Description
bool bool

True to require the TOTP step.

verify_mfa

verify_mfa(principal: PrincipalT, code: str) -> bool

Verify a submitted TOTP code for principal.

Only called when :meth:mfa_enabled returned True. The default rejects everything; backends that enable MFA must override it.

Parameters:

Name Type Description Default
principal PrincipalT

The authenticated principal.

required
code str

The 6-digit code from the authenticator app.

required

Returns:

Name Type Description
bool bool

True when the code is valid.

claim_mfa_step async

claim_mfa_step(session: AsyncSession, principal: PrincipalT, code: str) -> bool

Accept code for principal at most once.

The admin MFA route calls this, not :meth:verify_mfa, so a backend that can record which code it accepted refuses the same code twice. The default delegates to :meth:verify_mfa and keeps no record: a custom backend that stores its own TOTP state overrides this method to persist the accepted step, as :class:UserModelAuthBackend does.

Parameters:

Name Type Description Default
session AsyncSession

The request's DB session. A write is executed but not committed; the caller commits.

required
principal PrincipalT

The authenticated principal.

required
code str

The 6-digit code from the authenticator app.

required

Returns:

Name Type Description
bool bool

True when the code is valid and was not accepted

bool

before.

UserModelAuthBackend

UserModelAuthBackend(
    user_model: type[BaseUserModel],
    *,
    mfa_issuer: str = "Admin",
    mfa_window: int = 1,
    require_mfa: bool = False,
)

Bases: AdminAuthBackend[BaseUserModel]

Default backend backed by :class:BaseUserModel.

Authenticates by selecting the row whose email matches the inbound identifier (case-insensitive), verifying the password via :class:tempest_fastapi_sdk.PasswordUtils and enforcing both is_admin=True and is_active=True. The :attr:last_login_at column is stamped on every successful login.

Who counts as an admin is :meth:is_authorized — is_admin by default. A service that authorizes by its own role column overrides that one method instead of re-implementing :meth:authenticate and :meth:load_principal, which is where the timing-safe password check lives.

Parameters:

Name Type Description Default
user_model type[BaseUserModel]

The concrete model class. Must be a subclass of :class:BaseUserModel.

required

Initialize the backend.

Parameters:

Name Type Description Default
user_model type[BaseUserModel]

The user model to query.

required
mfa_issuer str

Issuer label used when verifying TOTP codes (matches what the authenticator app stored).

'Admin'
mfa_window int

TOTP clock-drift tolerance in 30s steps.

1
require_mfa bool

Refuse /admin to an account without MFA enrolled (:meth:mfa_enabled). Login answers "MFA enrollment required for /admin" (401, on the login page) — only after the password is right, like the other account checks — and :meth:load_principal drops the session of an account whose MFA was turned off after it signed in. The admin has no enrollment screen: enrollment happens out of band, through the /auth/mfa/enroll + /auth/mfa/confirm routes of :func:~tempest_fastapi_sdk.make_auth_router or tempest user create --require-mfa on the CLI. Default False: MFA is asked for only from accounts that enrolled.

False

Raises:

Type Description
TypeError

When user_model is not a subclass of :class:BaseUserModel.

is_authorized

is_authorized(user: BaseUserModel) -> bool

Whether user may use /admin.

The single authorization decision both :meth:authenticate and :meth:load_principal consult, so a revoked role ends the next request's session as well as the next login. Override it to authorize by something other than is_admin — a role column, a group membership already loaded on the row. It runs only for an active account whose password was right, and must not touch the database (it is synchronous on purpose: the row is already loaded).

Parameters:

Name Type Description Default
user BaseUserModel

The loaded account.

required

Returns:

Name Type Description
bool bool

True to let the account in. Default:

bool

bool(user.is_admin).

authenticate async

authenticate(session: AsyncSession, *, identifier: str, password: str) -> BaseUserModel

Verify credentials against the configured user model.

The password is checked before anything about the account is revealed. An unknown address pays a bcrypt check against a throwaway hash (:meth:PasswordUtils.dummy_verify, on one instance kept by the backend so the hash is built once, not per attempt), and every wrong password — unknown, non-admin, disabled or admin account — is refused with the same "Invalid credentials". Only a caller who already knows the password learns that the account is disabled, not authorized (:meth:is_authorized) or, under require_mfa=True, missing MFA enrollment. Checking is_active and is_admin first let anyone with a list of addresses read which ones are admins, and which are disabled, off the error message and the response time.

Parameters:

Name Type Description Default
session AsyncSession

A live DB session.

required
identifier str

The user's email.

required
password str

The plaintext password.

required

Returns:

Name Type Description
BaseUserModel BaseUserModel

The authenticated row with

BaseUserModel

attr:last_login_at already stamped.

Raises:

Type Description
AdminAuthError

On any rejection.

load_principal async

load_principal(session: AsyncSession, principal_id: str) -> BaseUserModel | None

Reload the user by ID, ensuring they still qualify for admin.

Returns None when the user no longer exists, has been deactivated, is no longer :meth:is_authorized, or — under require_mfa=True — turned MFA off after signing in.

Parameters:

Name Type Description Default
session AsyncSession

A live DB session.

required
principal_id str

The UUID hex string from the cookie.

required

Returns:

Type Description
BaseUserModel | None

BaseUserModel | None: The user row, or None.

is_admin_account

is_admin_account(target: object) -> bool

Whether target can sign into the admin itself.

A row of :attr:user_model answers what :meth:is_authorized answers, so a backend that authorizes by role refuses impersonating that role too; any row also counts when it carries a truthy is_admin.

Parameters:

Name Type Description Default
target object

The row the operator asked to enter as.

required

Returns:

Name Type Description
bool bool

True to refuse the impersonation.

load_account async

load_account(session: AsyncSession, account_id: str) -> BaseUserModel | None

Load the :attr:user_model row whatever its sign-in state.

Unlike :meth:load_principal, an inactive or MFA-less admin comes back, so :meth:is_admin_identity still refuses impersonating it.

Parameters:

Name Type Description Default
session AsyncSession

A live DB session.

required
account_id str

The account's id, as text.

required

Returns:

Type Description
BaseUserModel | None

BaseUserModel | None: The row, or None for an unknown or

BaseUserModel | None

malformed id.

principal_id

principal_id(principal: BaseUserModel) -> str

Return the id UUID hex for serialization.

Parameters:

Name Type Description Default
principal BaseUserModel

The authenticated row.

required

Returns:

Name Type Description
str str

The UUID as str.

credential_fingerprint

credential_fingerprint(principal: BaseUserModel) -> str | None

Fingerprint the password hash and the TOTP secret.

A new password writes a new bcrypt hash (fresh salt included), and re-enrolling MFA writes a new secret, so either change ends every admin session issued before it. The value never leaves the server as-is: the router stores only an HMAC of it keyed with the admin secret_key.

Parameters:

Name Type Description Default
principal BaseUserModel

The authenticated row.

required

Returns:

Type Description
str | None

str | None: The fingerprint.

mfa_enabled

mfa_enabled(principal: BaseUserModel) -> bool

Whether the user has completed MFA enrollment.

True when the user carries a populated totp_secret and a non-null totp_enabled_at (from :class:tempest_fastapi_sdk.MFAMixin). Users without the mixin simply never enable MFA.

Parameters:

Name Type Description Default
principal BaseUserModel

The authenticated row.

required

Returns:

Name Type Description
bool bool

True to require the TOTP step.

verify_mfa

verify_mfa(principal: BaseUserModel, code: str) -> bool

Verify code against the user's persisted TOTP secret.

Parameters:

Name Type Description Default
principal BaseUserModel

The authenticated row.

required
code str

The submitted authenticator code.

required

Returns:

Name Type Description
bool bool

True when the code is valid.

Raises:

Type Description
ImportError

When the [mfa] extra (pyotp) is not installed but a user has MFA enabled.

claim_mfa_step async

claim_mfa_step(session: AsyncSession, principal: BaseUserModel, code: str) -> bool

Accept code once, recording its step in totp_last_step.

Resolves the 30-second step code belongs to and stores it with one conditional UPDATE that only matches while the stored step is NULL or older, the same claim :class:~tempest_fastapi_sdk.UserAuthService uses for /auth/mfa/verify. The row count is the verdict, so a replayed code, or a stale copy of the row in another session, cannot be accepted twice.

Parameters:

Name Type Description Default
session AsyncSession

The request's DB session. The statement is executed but not committed; the caller commits.

required
principal BaseUserModel

The authenticated row.

required
code str

The submitted authenticator code.

required

Returns:

Name Type Description
bool bool

True when code matched a step inside the window

bool

that had not been accepted before, now recorded.

Raises:

Type Description
ImportError

When the [mfa] extra (pyotp) is not installed but a user has MFA enabled.

make_admin_router

make_admin_router(
    site: AdminSite,
    *,
    db: AsyncDatabaseManager,
    auth_backend: AdminAuthBackend[Any],
    secret_key: str,
    prefix: str = "/admin",
    session_store: SessionStore | None = None,
    cookie_secure: bool = True,
    export_max_rows: int = 5000,
    show_metrics: bool = True,
    show_logs: bool = False,
    log_dir: str | Path = "logs",
    access_policy: AdminAccessPolicy | None = None,
    action_policy: AdminActionPolicy | None = None,
    surface_policy: AdminSurfacePolicy | None = None,
    sql_shell: SqlShellService | None = None,
    tasks: TaskPanelService[Any] | None = None,
    storage: StorageBrowserService | None = None,
    mfa_throttle: AttemptThrottle | None = None,
    login_throttle: AttemptThrottle | Literal[False] | None = None,
    login_ip_throttle: AttemptThrottle | Literal[False] | None = None,
    trusted_ip_header: str | None = None,
    session_revocations: AdminSessionRevocations | None = None,
    search_results_per_model: int = ADMIN_SEARCH_RESULTS_PER_MODEL,
) -> APIRouter

Build the FastAPI router that mounts the admin site.

Routes attached:

  • GET {prefix}/login — login form.
  • POST {prefix}/login — login submit.
  • POST {prefix}/logout — clear session + redirect.
  • GET/POST {prefix}/mfa — TOTP challenge for MFA-enabled principals (between the password step and full access).
  • GET {prefix}/ — dashboard listing registered admins.
  • GET {prefix}/logs — structured application logs (when show_logs=True).
  • GET {prefix}/m/{slug}/ — list view (paginated, sortable, filterable).
  • GET {prefix}/m/{slug}/export.{fmt} — CSV/JSON export of the current (filtered + sorted) result set.
  • POST {prefix}/m/{slug}/bulk — bulk delete / activate / deactivate, or a custom action, on the selected rows; a custom action declared with schema= answers its input form first.
  • GET/POST {prefix}/m/{slug}/new — create form + submit (when can_create).
  • GET {prefix}/m/{slug}/{identity} — detail view.
  • GET/POST {prefix}/m/{slug}/{identity}/edit — edit form + submit (when can_edit).
  • POST {prefix}/m/{slug}/{identity}/delete — delete row (when can_delete).
  • GET/POST {prefix}/m/{slug}/{identity}/impersonate — confirm and enter the app as the row (when AdminModel(impersonate=...)).
  • GET {prefix}/m/{slug}/{identity}/restore/{entry_id} — the edit form pre-filled with the values an audit entry replaced (when audit_model and can_edit).
  • GET {prefix}/search — global search across every model with search_fields.
  • Static files under {prefix}/static named admin_static.
  • GET {prefix}/_ssr/htmx.js — the HTMX bundled in the SDK (ssr/_static/htmx.min.js), served without a session because the login page loads it too. No admin page fetches a script from a third-party host.

Parameters:

Name Type Description Default
site AdminSite

The configured registry.

required
db AsyncDatabaseManager

Active DB manager (used for both sessions and the readiness check).

required
auth_backend AdminAuthBackend[Any]

Backend resolving login credentials to a principal.

required
secret_key str

Secret used to sign the session cookie. 32 bytes minimum.

required
prefix str

URL prefix; defaults to "/admin".

'/admin'
session_store SessionStore | None

Override the default :class:SignedCookieSessionStore.

None
cookie_secure bool

Set the Secure flag on cookies. Default True; disable only for local HTTP dev.

True
export_max_rows int

Hard cap on rows returned by the CSV/JSON export endpoint. Exports beyond this are truncated (a header/log notes it) to bound memory.

5000
show_metrics bool

When True (default), the dashboard renders a CPU/RAM/disk panel via MetricsUtils — silently omitted when the [metrics] extra is not installed. Set False to skip the per-request sample entirely.

True
show_logs bool

When True, a GET {prefix}/logs page is mounted and a "Logs" entry appears in the sidebar. It reads the structured JSON files written by configure_logging (see log_dir) and renders them filtered + paginated. Defaults to False (opt-in — log payloads expose tracebacks and request metadata).

False
log_dir str | Path

Directory holding the structured log files, matching the log_dir passed to configure_logging. Only consulted when show_logs is True. Defaults to "logs". When the directory has no log files yet the page renders an empty state.

'logs'
access_policy AdminAccessPolicy | None

Optional granular RBAC hook asked (principal, admin, AdminPermissionEnum) for every model action. None (default) allows everything (subject to the AdminModel.can_* flags). A policy that denies an action yields 403 and hides the model from the dashboard + nav for VIEW. Composes with the can_* flags — both must allow. It also governs what a page renders of another model: inline tables need VIEW on the child (an editable inline's add row CREATE, its delete box DELETE), and foreign-key selects, list filters and autocomplete need VIEW on the referenced admin.

None
action_policy AdminActionPolicy | None

Hook asked (principal, admin, AdminAction) before a custom action runs and when the list builds its action menu. When set, a custom action needs VIEW on the model (access_policy) and this policy's approval, and no longer EDIT: one action can be granted without the edit form, and one role can run an action another cannot. A denied action is left out of the menu and its POST answers 403. None (default) keeps asking EDIT for every custom action.

None
surface_policy AdminSurfacePolicy | None

Hook asked (principal, AdminSurfaceEnum) before the SQL console, the task panel (cancel included) or the logs page (export included) is served; a denial yields 403 and drops the sidebar entry. None (default) allows every surface when access_policy is also None, and denies every surface once an access_policy is configured: a principal restricted to some models would otherwise read any table through the console. Pass one to grant the surfaces to the roles that should have them.

None
sql_shell SqlShellService | None

When given, mounts the SQL console at GET/POST {prefix}/sql and adds its nav entry.

None
tasks TaskPanelService[Any] | None

When given, mounts the task panel at GET {prefix}/tasks (declared schedule + persisted runs), the run detail at GET {prefix}/tasks/{job_id} and the cancel action at POST {prefix}/tasks/{job_id}/cancel, and adds its nav entry. Either half of the service may be absent; a section with no source is not rendered.

None
storage StorageBrowserService | None

When given, mounts the storage browser at GET {prefix}/storage (folder listing), GET {prefix}/storage/object (one object: metadata, preview, text editor), GET {prefix}/storage/raw (the bytes, inline only for inline-safe types) and the POST writes under {prefix}/storage/ (upload, replace, edit, rename, delete), and adds its nav entry. A read_only service answers 403 to every write.

None
mfa_throttle AttemptThrottle | None

Failure budget for the POST {prefix}/mfa challenge, keyed on the principal, so a fresh password login does not reset it. Once spent, the challenge answers 429 with Retry-After before the code is checked; a correct code resets the key. None (default) allows ADMIN_MFA_THROTTLE_MAX_ATTEMPTS (5) wrong codes per ADMIN_MFA_THROTTLE_WINDOW_SECONDS (900) on an :class:~tempest_fastapi_sdk.InMemoryThrottleBackend, which counts per process: behind more than one worker, pass an :class:~tempest_fastapi_sdk.AttemptThrottle on Redis.

None
login_throttle AttemptThrottle | Literal[False] | None

Failure budget for POST {prefix}/login per identifier, keyed "login:<sha256 of the normalized identifier>" (:func:~tempest_fastapi_sdk.login_throttle_key, the key make_auth_router uses). Each attempt reserves one unit before the password is checked and a successful login clears the key, so only failures accumulate; the attempt past max_attempts re-renders the login page with 429 and Retry-After whatever the password, so the response is no oracle. Spent the same way for an identifier with no account. None (default) allows ADMIN_LOGIN_THROTTLE_MAX_ATTEMPTS (5) per ADMIN_LOGIN_THROTTLE_WINDOW_SECONDS (900) on an :class:~tempest_fastapi_sdk.InMemoryThrottleBackend — per process, so pass one on Redis behind more than one worker. False turns it off.

None
login_ip_throttle AttemptThrottle | Literal[False] | None

Failure budget for POST {prefix}/login per client IP ("admin-login-ip:<addr>"), for one source trying many identifiers. Read before the identifier budget is spent and counted only on a refused login; a success does not clear it, since one valid account would otherwise reset the counter between guesses. None (default) turns it on with ADMIN_LOGIN_IP_THROTTLE_MAX_ATTEMPTS (20) per 900 s in memory only when trusted_ip_header is set, and leaves it off otherwise: behind a reverse proxy without that header every operator shares the proxy's address, and twenty bad logins from anyone would lock all of them out. A throttle passed explicitly always applies. False turns it off.

None
trusted_ip_header str | None

Single edge-set header holding the real client IP (e.g. "x-real-ip") for login_ip_throttle. None uses the transport peer. See :func:~tempest_fastapi_sdk.get_client_ip.

None
session_revocations AdminSessionRevocations | None

Where POST {prefix}/logout marks the session it ends; every request refuses a marked session, so a copy of the cookie stops working at logout instead of at max_age. None (default) keeps the marks on an :class:~tempest_fastapi_sdk.InMemoryThrottleBackend for the store's max_age_seconds — per process, so behind more than one worker pass AdminSessionRevocations(redis_client). Independently of this, the session is bound to :meth:AdminAuthBackend.credential_fingerprint, so a password change ends every session issued before it, on every replica.

None
search_results_per_model int

Rows the global search lists per model. Defaults to :data:ADMIN_SEARCH_RESULTS_PER_MODEL (5).

ADMIN_SEARCH_RESULTS_PER_MODEL

Returns:

Name Type Description
APIRouter APIRouter

A router ready to attach via app.include_router.

Raises:

Type Description
ImportError

When the [admin] extra is not installed, so Jinja2 is unavailable to render the templates.

ValueError

When search_results_per_model is below 1.

ADMIN_SEARCH_RESULTS_PER_MODEL module-attribute

ADMIN_SEARCH_RESULTS_PER_MODEL: int = 5

Rows the global search (GET {prefix}/search) lists per model.

The default of make_admin_router(search_results_per_model=...); the model's own list, linked from each group, holds the rest.

ADMIN_SEARCH_MAX_QUERY_LENGTH module-attribute

ADMIN_SEARCH_MAX_QUERY_LENGTH: int = 200

Longest global-search term, in characters, that runs a query.

ADMIN_SEARCH_MAX_TERMS module-attribute

ADMIN_SEARCH_MAX_TERMS: int = 8

Most words a global-search term may have and still run a query.

Every word becomes one escaped ILIKE per search field of every searchable model, so the cap bounds the statement the search can build.

discover_models

discover_models(
    source: str | ModuleType, *, exclude: Sequence[type[BaseModel] | str] = ()
) -> list[type[BaseModel]]

Collect every concrete BaseModel subclass under source.

Parameters:

Name Type Description Default
source str | ModuleType

Either a dotted module path (e.g. "src.db.models") or an already-imported module/package. When it is a package, its submodules are imported and swept too.

required
exclude Sequence[type[BaseModel] | str]

Models to skip — each entry may be the model class, its class name, or its table name. Useful to hide a model that should not appear in the admin (e.g. an audit-log table).

()

Returns:

Type Description
list[type[BaseModel]]

list[type[BaseModel]]: Concrete mapped models, de-duplicated by

list[type[BaseModel]]

table name and ordered by table name for a stable nav.

Raises:

Type Description
ModuleNotFoundError

When source is a dotted path that cannot be imported.

AdminSession dataclass

AdminSession(
    principal_id: str,
    issued_at: float,
    csrf_token: str,
    mfa_pending: bool = False,
    session_id: str = _new_session_id(),
    credential_digest: str = "",
)

Authenticated admin session payload stored in the cookie.

Attributes:

Name Type Description
principal_id str

Identifier returned by :meth:AdminAuthBackend.principal_id at login.

issued_at float

Unix timestamp when the session was issued.

csrf_token str

Per-session CSRF token; required on all POST submissions inside the admin.

mfa_pending bool

True after the password step when the principal has MFA enabled but has not yet passed the TOTP challenge. A pending session grants NO access to admin pages — it only authorizes the /mfa challenge.

session_id str

Random id of this session, the handle :class:AdminSessionRevocations marks on logout. A fresh one is drawn for every new session; a cookie issued before the field existed decodes to "" and cannot be revoked.

credential_digest str

:func:admin_credential_digest of the principal's credential fingerprint at sign-in. The router compares it on every request, so a password (or MFA secret) change ends every session issued before it. "" when the backend exposes no fingerprint.

to_payload

to_payload() -> dict[str, Any]

Serialize the session for cookie storage.

Returns:

Type Description
dict[str, Any]

dict[str, Any]: A JSON-serializable dict.

from_payload classmethod

from_payload(payload: dict[str, Any]) -> AdminSession | None

Build a session from a deserialized cookie payload.

Parameters:

Name Type Description Default
payload dict[str, Any]

The decoded cookie value.

required

Returns:

Type Description
AdminSession | None

AdminSession | None: The parsed session, or None when

AdminSession | None

the payload is malformed.

AdminSessionRevocations

AdminSessionRevocations(
    backend: ThrottleBackend, *, ttl_seconds: int = ADMIN_SESSION_MAX_AGE_SECONDS
)

Server-side list of admin sessions ended by logout.

The default admin cookie is stateless: clearing it on logout only asks the browser to forget it, and a copy taken earlier would keep working until max_age. POST /logout therefore marks the session's :attr:AdminSession.session_id here, and every request checks the mark before trusting the cookie. A mark lives as long as the cookie could, then expires on its own.

Storage is any :class:~tempest_fastapi_sdk.utils.throttle.ThrottleBackend — the same shape redis.asyncio.Redis and :class:~tempest_fastapi_sdk.utils.throttle.InMemoryThrottleBackend have. The in-memory one is per process: behind more than one worker or replica, pass the Redis client so a logout served by one is seen by all.

Initialize the list.

Parameters:

Name Type Description Default
backend ThrottleBackend

Key/value storage with incr, expire and get.

required
ttl_seconds int

How long a mark is kept; at least the session lifetime.

ADMIN_SESSION_MAX_AGE_SECONDS

revoke async

revoke(session: AdminSession) -> None

Mark session as ended. A session without an id is skipped.

Parameters:

Name Type Description Default
session AdminSession

The session being logged out.

required

is_revoked async

is_revoked(session: AdminSession) -> bool

Whether session was ended by a logout.

Parameters:

Name Type Description Default
session AdminSession

The session the request carries.

required

Returns:

Name Type Description
bool bool

True when a mark exists for its id.

AdminSubmissionNonces

AdminSubmissionNonces(backend: ThrottleBackend, *, ttl_seconds: int)

Single-use tokens that stop a reloaded POST from running twice.

A form whose answer is the POST itself — the page that shows a new API key once — is resubmitted by the browser on reload, and before #739 that ran the handler again and minted a second key. Each such form now carries a nonce (:meth:issue); the POST calls :meth:consume before running, and only the first call for a nonce gets True.

consume is one incr on the same :class:~tempest_fastapi_sdk.utils.throttle.ThrottleBackend the session revocations use, so the check is atomic and, with the Redis client passed to :class:AdminSessionRevocations, shared across workers. With the default in-memory backend it is per process: a resend that lands on another worker runs again.

Initialize the store.

Parameters:

Name Type Description Default
backend ThrottleBackend

Key/value storage with incr, expire and get.

required
ttl_seconds int

How long a used nonce is remembered; at least the session lifetime, since a form cannot outlive it.

required

issue staticmethod

issue() -> str

Return a fresh nonce for a form.

Returns:

Name Type Description
str str

A URL-safe random token.

consume async

consume(session: AdminSession, nonce: str) -> bool

Mark nonce used for session; True only the first time.

Parameters:

Name Type Description Default
session AdminSession

The session submitting the form; the key is scoped to it so one operator's nonce never collides with another's.

required
nonce str

The value the form carried.

required

Returns:

Name Type Description
bool bool

True when this is the first submission of the nonce,

bool

False for a resubmission, an empty value or one longer than

bool

data:ADMIN_SUBMISSION_NONCE_MAX_LENGTH.

admin_credential_digest

admin_credential_digest(secret_key: str, fingerprint: str | None) -> str

Bind a principal's credential fingerprint to the admin secret.

The cookie carries this digest, never the fingerprint itself (for :class:~tempest_fastapi_sdk.admin.auth.UserModelAuthBackend the fingerprint contains the password hash). Keyed with secret_key, so a cookie holder cannot test guesses against it.

Parameters:

Name Type Description Default
secret_key str

The admin signing key.

required
fingerprint str | None

What :meth:~tempest_fastapi_sdk.admin.auth.AdminAuthBackend.credential_fingerprint returned. None means the backend binds nothing.

required

Returns:

Name Type Description
str str

32 hex characters, or "" when fingerprint is None.

SignedCookieSessionStore

SignedCookieSessionStore(
    secret_key: str,
    *,
    cookie_name: str = "tempest_admin",
    max_age_seconds: int = ADMIN_SESSION_MAX_AGE_SECONDS,
    secure: bool = True,
    same_site: SameSite = "lax",
    path: str = "/admin",
)

Bases: SessionStore

Default session store using a single signed JSON cookie.

The cookie is signed with HMAC-SHA256 via :mod:itsdangerous so tampered payloads are rejected. Cookies are scoped to HttpOnly + SameSite=Lax and may be flagged Secure for HTTPS deployments; signed payloads also carry their own expiration via the max_age argument passed to loads.

Parameters:

Name Type Description Default
secret_key str

Shared secret used to sign the cookie. MUST be at least 32 bytes; production deployments should source it from a secrets manager.

required
cookie_name str

Cookie name. Defaults to "tempest_admin".

'tempest_admin'
max_age_seconds int

Session lifetime; cookies older than this are rejected by :meth:load.

ADMIN_SESSION_MAX_AGE_SECONDS
secure bool

Whether to flag the cookie Secure. Default True — disable in local-only HTTP setups.

True
same_site SameSite

SameSite policy — "lax" (default), "strict" or "none", matched ignoring case and stored lower-cased.

'lax'
path str

Cookie path. Defaults to "/admin".

'/admin'

Initialize the store.

Parameters:

Name Type Description Default
secret_key str

The signing key.

required
cookie_name str

Cookie name.

'tempest_admin'
max_age_seconds int

Session lifetime.

ADMIN_SESSION_MAX_AGE_SECONDS
secure bool

Whether to set Secure.

True
same_site SameSite

SameSite policy, matched ignoring case.

'lax'
path str

Cookie path scope.

'/admin'

Raises:

Type Description
ValueError

When secret_key is empty or too short, or same_site is not "lax", "strict" or "none".

ImportError

When the [admin] extra is not installed.

load

load(request: Request) -> AdminSession | None

Decode and validate the inbound session cookie.

Parameters:

Name Type Description Default
request Request

The inbound request.

required

Returns:

Type Description
AdminSession | None

AdminSession | None: The session, or None when the

AdminSession | None

cookie is absent, expired or tampered with.

save

save(response: Response, session: AdminSession) -> None

Sign and attach the session cookie to response.

Parameters:

Name Type Description Default
response Response

The outbound response.

required
session AdminSession

The session to persist.

required

clear

clear(response: Response) -> None

Expire the session cookie.

Parameters:

Name Type Description Default
response Response

The outbound response.

required

issue

issue(principal_id: str, csrf_token: str, *, mfa_pending: bool = False) -> AdminSession

Build a new session ready to :meth:save.

Parameters:

Name Type Description Default
principal_id str

Identifier of the authenticated user.

required
csrf_token str

CSRF token to bind to the session.

required
mfa_pending bool

Whether the session still needs to pass the TOTP challenge before granting access.

False

Returns:

Name Type Description
AdminSession AdminSession

The fresh session.

AdminLoginCSRF

AdminLoginCSRF(
    secret_key: str,
    *,
    secure: bool = True,
    path: str = "/admin",
    max_age_seconds: int = ADMIN_LOGIN_CSRF_MAX_AGE_SECONDS,
)

CSRF token for the login form, which runs before any session exists.

Every other admin form checks the token stored in the session. The login form cannot: there is no session yet, and without a token a page on another site could make an operator's browser post the attacker's credentials to /login — the response sets the admin cookie, and the operator ends up working in the attacker's account (login CSRF). SameSite=Lax does not prevent it: it restricts which cookies a cross-site POST sends, not the cookie its response sets.

The token is random, signed with a timestamp into a short-lived cookie scoped to the admin prefix, and repeated in a hidden form field; the submit compares the two in constant time. A cross-site page cannot read the cookie, so it cannot fill the field.

Independent of the configured :class:SessionStore, so a deployment that swaps the store keeps the protection.

Initialize the signer.

Parameters:

Name Type Description Default
secret_key str

The admin signing key; at least 32 bytes, the rule :class:SignedCookieSessionStore applies.

required
secure bool

Whether to flag the cookie Secure.

True
path str

Cookie path scope — the admin prefix.

'/admin'
max_age_seconds int

How long a rendered form stays valid.

ADMIN_LOGIN_CSRF_MAX_AGE_SECONDS

Raises:

Type Description
ValueError

When secret_key is empty or too short.

ImportError

When the [admin] extra is not installed.

current

current(request: Request) -> str | None

Return the token the request's cookie carries, if still valid.

Parameters:

Name Type Description Default
request Request

The inbound request.

required

Returns:

Type Description
str | None

str | None: The token, or None when the cookie is absent,

str | None

expired or tampered with.

issue

issue(request: Request) -> str

Return the token to embed in the form being rendered.

Reuses the request's valid token, so two tabs on the login page do not invalidate each other; mints a new one otherwise.

Parameters:

Name Type Description Default
request Request

The inbound request.

required

Returns:

Name Type Description
str str

The token for the hidden field.

attach

attach(response: Response, token: str) -> None

Set the signed cookie carrying token on response.

Re-signing on every render restarts the expiry, so a form that was just re-rendered after an error is good for the full window.

Parameters:

Name Type Description Default
response Response

The outbound response.

required
token str

The token embedded in the form.

required

verify

verify(request: Request, submitted: str) -> bool

Check the submitted field against the cookie, in constant time.

Parameters:

Name Type Description Default
request Request

The inbound request.

required
submitted str

The csrf_token form field.

required

Returns:

Name Type Description
bool bool

True only when the cookie is valid and matches.

clear

clear(response: Response) -> None

Drop the pre-login cookie once a session exists.

Parameters:

Name Type Description Default
response Response

The outbound response.

required

AdminAction dataclass

AdminAction(
    name: str,
    label: str,
    handler: AnyActionHandler,
    dangerous: bool = False,
    schema: type[BaseModel] | None = None,
)

A registered custom action: metadata + handler.

Attributes:

Name Type Description
name str

Stable identifier (form value); unique per model.

label str

Text shown in the bulk-action dropdown.

handler AnyActionHandler

The async function to run — (ctx), or (data, ctx) when schema is set.

dangerous bool

When True, the UI marks it as destructive (a stronger confirm prompt).

schema type[BaseModel] | None

The input the operator fills in before the action runs; None runs it straight from the list.

AdminAuthError

AdminAuthError(message: str = 'Invalid credentials', *, status_code: int = 401)

Bases: Exception

Raised by authentication backends when credentials are rejected.

Captures the user-facing message the login template should render alongside the HTTP status code (default 401). Specific failure reasons should map to subclasses of this base exception for granular templating.

Initialize the error.

Parameters:

Name Type Description Default
message str

The end-user-facing message.

'Invalid credentials'
status_code int

HTTP status code to attach.

401

FieldRef module-attribute

FieldRef = InstrumentedAttribute[Any] | str

A column reference: either a mapped attribute (Model.email) or its string key ("email"). Column references give editor autocomplete and typo-checking; strings remain accepted for dynamic configuration.

OrderRef module-attribute

OrderRef = InstrumentedAttribute[Any] | UnaryExpression[Any] | str

An ordering reference: a column (Model.created_at, ascending), a direction-wrapped column (desc(Model.created_at)), or a Django-style string ("created_at" / "-created_at").

BRLocationMap dataclass

BRLocationMap(
    title: str,
    model: type[BRLocationMixin],
    *,
    where: Callable[[], ColumnElement[bool]] | None = None,
    city_limit: int = 50,
    value_label: str = "users",
)

A map page of where a model's rows are in Brazil.

title and model are positional; the rest is keyword-only.

The page needs VIEW on the model under the access_policy (it shows the model's data, aggregated), asked of the model's registered :class:~tempest_fastapi_sdk.admin.AdminModel or, when the model is not registered, of a throwaway AdminModel(model).

Attributes:

Name Type Description
title str

The page heading and the sidebar label.

model type[BRLocationMixin]

A model with :class:~tempest_fastapi_sdk.geo.BRLocationMixin.

where Callable[[], ColumnElement[bool]] | None

Builds an extra filter for every count (lambda: UserModel.is_active.is_(True)); a callable, so the expression is built per request.

city_limit int

How many cities the bubbles and the table show, largest first.

value_label str

Word after each number in the tooltips and the tables ("usuários").

slug str

The URL segment, derived from title.

Raises:

Type Description
TypeError

When model does not have the mixin's columns.

ValueError

When city_limit is below 1, or title yields an empty slug.

collect async

collect(session: AsyncSession) -> BRLocationDistributionSchema

Count the model's rows per state and city.

Parameters:

Name Type Description Default
session AsyncSession

The admin's database session.

required

Returns:

Name Type Description
BRLocationDistributionSchema BRLocationDistributionSchema

The counts, cities capped at

BRLocationDistributionSchema

attr:city_limit.

page_context

page_context(distribution: BRLocationDistributionSchema) -> dict[str, Any]

Build what the page template renders from the counts.

Parameters:

Name Type Description Default
distribution BRLocationDistributionSchema

The counts.

required

Returns:

Type Description
dict[str, Any]

dict[str, Any]: svg (the map markup, escaped inside),

dict[str, Any]

legend, distribution and value_label.

AdminTheme dataclass

AdminTheme(
    accent: str = "#2563eb",
    accent_hover: str = "#1d4ed8",
    danger: str = "#b91c1c",
    header_bg: str = DEFAULT_HEADER_BG,
    sidebar_bg: str | None = None,
    header_fg: str | None = None,
    page_bg: str | None = None,
    radius: str = "8px",
    font_family: str | None = None,
    logo_url: str | None = None,
    logo_alt: str = "Logo",
    favicon_url: str | None = None,
    footer_text: str = "Powered by tempest-fastapi-sdk",
    dark_mode: bool = False,
    custom_css_url: str | None = None,
)

Typed appearance overrides for the admin panel.

Every field maps to a CSS custom property on :root (or to a piece of chrome like the logo / footer). All fields have sensible defaults that reproduce the stock look, so AdminTheme() is a no-op and you only set what you want to change.

Attributes:

Name Type Description
accent str

Primary accent color — links, primary buttons, active sidebar item. Any CSS color ("#7c3aed", "rebeccapurple", "rgb(124 58 237)").

accent_hover str

Hover/active shade of :attr:accent.

danger str

Color for destructive actions and error messages.

header_bg str

Background of the top header band. Light by default; the header and sidebar text switch to light on a dark hex value on their own.

sidebar_bg str | None

Background of the left sidebar. Falls back to :attr:header_bg when None so the chrome reads as one surface.

header_fg str | None

Text color on the header and sidebar. None picks dark or light text from the luminance of :attr:header_bg / :attr:sidebar_bg; set it when the background is not a hex value and the guess is wrong.

page_bg str | None

Main content background. None uses the mode default (light grey, or near-black when :attr:dark_mode is on).

radius str

Border-radius applied to buttons, inputs, cards and tables ("8px", "0.75rem", "0" for square).

font_family str | None

CSS font-family for the whole panel. None keeps the system font stack.

logo_url str | None

URL of an image shown in the header instead of the brand text. None shows the text brand.

logo_alt str

alt text for the logo image.

favicon_url str | None

URL of the browser-tab favicon. None lets the browser use its default.

footer_text str

Text shown in the page footer.

dark_mode bool

When True, the content surfaces (page background, cards, text, table rows, inputs, borders) switch to a dark palette, and so does the chrome while :attr:header_bg is the default. :attr:accent and the other colors still apply.

custom_css_url str | None

URL of an extra stylesheet linked after the theme, so it overrides everything. The escape hatch for anything the typed fields do not cover.

css_variables

css_variables() -> dict[str, str]

Return the :root custom properties this theme sets.

Returns:

Type Description
dict[str, str]

dict[str, str]: Mapping of CSS variable name to value. Only

dict[str, str]

the always-present variables are included here; mode- and

dict[str, str]

font-dependent rules are emitted by :meth:to_css.

to_css

to_css() -> str

Render the full <style> body for this theme.

Combines the :meth:css_variables :root block with the optional dark-mode surface overrides. The result is injected verbatim inside a <style> element in the page <head>.

Returns:

Name Type Description
str str

CSS text. Empty-safe — a default AdminTheme() still

str

returns a valid (no-op-equivalent) block.

Notes

The dark surface block covers the content area; the chrome goes dark through :meth:css_variables (--tempest-bg). The block is skipped entirely when the project pinned its own page_bg — an explicit value always wins.