tempest_fastapi_sdk.admin¶
O painel admin estilo Django: site, model admin, ações, políticas de acesso, auditoria e páginas.
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 |
brand |
str | None
|
Optional override for the centered
header brand text. Falls back to :attr: |
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: |
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 |
Initialize the site.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
title
|
str
|
Branding text — used in the page |
'Admin'
|
brand
|
str | None
|
Optional text for the centered header
brand. |
None
|
index_subtitle
|
str | None
|
Dashboard and login subtitle.
|
None
|
site_url
|
str | None
|
Optional outbound link rendered in the admin header. |
None
|
theme
|
AdminTheme | None
|
Typed appearance overrides.
|
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
|
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 |
()
|
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 |
()
|
locale
|
AdminLocale
|
Language of the panel's own text —
labels, buttons, empty states, flash messages and the
errors the router renders (see
:mod: |
DEFAULT_ADMIN_LOCALE
|
recent_activity
|
int | None
|
Show the last |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
brand_text
property
¶
Return the centered header brand text.
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
:attr: |
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 |
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.
|
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
|
**admin_kwargs
|
Any
|
Forwarded to every |
{}
|
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 |
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
|
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 ( |
()
|
readonly_fields
|
Sequence[FieldRef]
|
Fields locked in the detail view. |
()
|
ordering
|
OrderRef | None
|
Default ordering. Accepts a column
(ascending), |
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'
|
repository_class
|
type[BaseRepository[Any]] | None
|
Concrete
repository. |
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
|
None
|
can_create
|
bool
|
Whether the admin exposes the column create
form + POST endpoint. |
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 |
None
|
can_edit
|
bool
|
Whether the admin exposes the edit form + POST
endpoint. Default |
True
|
can_delete
|
bool
|
Whether the admin exposes the delete action.
Default |
True
|
can_toggle_active
|
bool
|
Whether the list view offers the
built-in "Activate" / "Deactivate" bulk actions (they also need
|
True
|
can_import
|
bool
|
Whether the admin exposes a CSV import page
( |
False
|
actions
|
Sequence[AnyActionHandler]
|
Custom bulk actions —
functions decorated with
:func: |
()
|
upload_fields
|
Sequence[FieldRef]
|
String columns rendered as
file inputs in the create/edit form. The uploaded file is
saved through |
()
|
upload_storage
|
UploadStorage | None
|
Backend used to persist
uploaded files ( |
None
|
upload_accept
|
Mapping[FieldRef, Sequence[str]] | None
|
MIME types
an upload field takes ( |
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 |
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 |
None
|
audit_model
|
type[BaseAuditLogModel] | None
|
When set, the detail
view renders a per-row change timeline read from this audit
table (matched on |
None
|
choices
|
Mapping[FieldRef, ChoiceSource]
|
Columns rendered as a
|
None
|
autocomplete_fields
|
Sequence[FieldRef]
|
Foreign-key columns
rendered as a typed search box (HTMX) instead of a
|
()
|
inlines
|
Sequence[Inline]
|
Related child models listed on this
model's detail view (Django |
()
|
lenses
|
Sequence[Lens]
|
Named saved list-view presets (Nova-style
lenses) rendered as tabs above the list; each applies its
filters + ordering via |
()
|
display_timezone
|
str | None
|
IANA name of the timezone the
operator reads and types datetimes in (for example
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 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
|
exclude_fields
|
Sequence[FieldRef]
|
Columns the panel never
shows or accepts — for a credential that is not a password,
like a push subscription's
Hiding the timeline's rows is not enough on its own: the audit
table itself would still hold the value. With 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
( |
()
|
row_scope
|
AdminRowScope | None
|
Called with the signed-in principal and this
admin on every request that reads or writes a row of :attr: |
None
|
m2m_fields
|
Sequence[FieldRef]
|
Many-to-many relationships
( |
()
|
related_counts
|
Sequence[RelatedCount]
|
Columns of the list view
counting the child rows that reference each row
(:class: |
()
|
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 ( |
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 |
()
|
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
( |
None
|
impersonate_account
|
AdminImpersonateAccount | None
|
Maps the row
to the account the handler enters as ( |
None
|
count_strategy
|
AdminCountStrategy
|
How the list counts its rows:
|
EXACT
|
Raises:
| Type | Description |
|---|---|
TypeError
|
When |
ValueError
|
When |
Build and validate the configuration. See class docstring.
creates
property
¶
Whether the list shows "+ New": the column form or a handler.
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
|
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 |
required |
Returns:
| Type | Description |
|---|---|
Lens | None
|
Lens | None: The matching lens. |
scope_for
async
¶
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 |
Raises:
| Type | Description |
|---|---|
AdminRowScopeError
|
When the scope returns (or awaits to)
anything that is not a SQLAlchemy clause, |
get_verbose_name
¶
Return the configured (or auto-derived) singular display name.
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The display name. |
get_verbose_name_plural
¶
Return the configured (or auto-derived) plural display name.
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The plural display name. |
get_slug
¶
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
¶
Return every mapped column name on :attr:model.
Returns:
| Type | Description |
|---|---|
list[str]
|
list[str]: Column keys in declaration order. |
hidden_field_names
¶
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
¶
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
¶
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]: |
set[str]
|
returns for |
editable_field_names
¶
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 |
None
|
Returns:
| Type | Description |
|---|---|
list[str]
|
list[str]: Editable column keys in declaration order. |
insertable_secret_names
¶
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 |
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 |
AdminAction | None
|
custom action with that name is registered. |
ChoiceSource
module-attribute
¶
The fixed values of a choices field: an Enum class, or a sequence
of strings or (value, label) pairs.
EditValidator
module-attribute
¶
(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
¶
(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
¶
(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: |
required |
ttl
|
timedelta
|
Token lifetime; defaults to
:data: |
ADMIN_IMPERSONATION_TTL
|
Returns:
| Name | Type | Description |
|---|---|---|
AdminImpersonateHandler |
AdminImpersonateHandler
|
The handler to pass as |
AdminImpersonateHandler
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
ADMIN_IMPERSONATION_TTL
module-attribute
¶
Default lifetime of the token :func:make_jwt_impersonation_handler signs.
ADMIN_IMPERSONATION_EVENT
module-attribute
¶
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
¶
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
¶
Marker :func:make_jwt_impersonation_handler replaces with the token.
AdminLocale
module-attribute
¶
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
¶
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: |
required |
key
|
str
|
The catalog key, such as |
required |
**params
|
Any
|
Values for the template's |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The formatted text. |
admin_plural
¶
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: |
required |
key
|
str
|
The catalog key without the |
required |
count
|
int
|
The number the text describes. |
required |
**params
|
Any
|
Further |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The formatted text. |
ADMIN_IMPORT_MAX_BYTES
module-attribute
¶
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
¶
How long a preview can be confirmed before the file must be sent again.
ADMIN_IMPORT_PREVIEW_ROWS
module-attribute
¶
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 |
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
|
False
|
Raises:
| Type | Description |
|---|---|
TypeError
|
When |
get_slug
¶
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
¶
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 |
filters |
dict[str, Any]
|
Column name to the value the tab's rows must
match, ANDed into the query, e.g.
|
order_by |
str | None
|
Column to order by; |
label |
str | None
|
Tab label; defaults to |
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.
|
None
|
order_by
|
str | None
|
Ordering column ( |
None
|
label
|
str | None
|
Tab label. |
None
|
RelatedCount
¶
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 ( |
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 ( |
required |
label
|
str | None
|
Column heading. |
None
|
Raises:
| Type | Description |
|---|---|
TypeError
|
When |
ValueError
|
When the column carries no |
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
¶
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
¶
A dashboard business-metric card.
Attributes:
| Name | Type | Description |
|---|---|---|
label |
str
|
The card heading. |
compute |
CardCompute
|
Async function returning the card data —
a :class: |
help_text |
str | None
|
Optional sub-label shown under the value. |
MetricValue
dataclass
¶
A single headline number.
Attributes:
| Name | Type | Description |
|---|---|---|
value |
Any
|
The value to show (number or preformatted string). |
unit |
str | None
|
Optional unit suffix ( |
MetricTrend
dataclass
¶
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
¶
Return value - previous.
Returns:
| Name | Type | Description |
|---|---|---|
float |
float
|
The absolute change. |
pct
property
¶
Return the percentage change, or None when undefined.
Returns:
| Type | Description |
|---|---|
float | None
|
float | None: |
float | None
|
|
direction
property
¶
Return the trend direction.
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
|
MetricPartition
dataclass
¶
A breakdown of a total across labeled segments.
Attributes:
| Name | Type | Description |
|---|---|---|
segments |
list[tuple[str, float]]
|
|
total
property
¶
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: |
provider |
MetricsProvider
|
Builds the service from the admin's database session. |
method |
str
|
The service method that returns |
thresholds |
Mapping[str, Threshold]
|
Field name → bands. Applies to
a number or to the current value of a :class: |
units |
Mapping[str, str]
|
Field name → unit shown after a number
( |
slug |
str
|
The URL segment, derived from |
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
collect
async
¶
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: |
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: |
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]]
|
|
list[tuple[str, str | None, CardData, MetricLevelEnum | None]]
|
for a field with no threshold or no numeric value. |
MetricsProvider
module-attribute
¶
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
¶
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 ( |
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
|
|
MetricLevelEnum
¶
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 |
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
|
required |
Returns:
| Name | Type | Description |
|---|---|---|
AdminAction |
AdminAction
|
The attached metadata + handler. |
Raises:
| Type | Description |
|---|---|
TypeError
|
When |
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 — |
secrets |
Sequence[AdminSecret]
|
Values to reveal once. Any sequence is accepted (a list included) and stored as a tuple. |
AdminSecret
dataclass
¶
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 ( |
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 |
handler |
CreateHandlerFunc
|
The async function that creates the record. |
label |
str | None
|
Text of the "+ New" button and the form
heading; |
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 bycorrelation_id; - no "Activate" / "Deactivate" bulk actions, and
is_activeread-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_keyan upload that takes only a PDF (declared typeapplication/pdfand bytes starting%PDF-), downloadable from the row's page, and refused once the row is no longerPENDING;rejection_reasoneditable while the row isPENDING; 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, withledger_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
|
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 |
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: |
required |
hooks
|
ManualPayoutHooks | None
|
Callbacks; |
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; |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
ActionHandler |
ActionHandler
|
The decorated action. |
MARK_PAID_ACTION
module-attribute
¶
Name of the "mark as paid" action (the bulk form's value).
RECEIPT_CONTENT_TYPES
module-attribute
¶
What the receipt field takes: a PDF, checked by type and by %PDF-.
REJECT_ACTION
module-attribute
¶
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
|
'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: |
None
|
Returns:
| Type | Description |
|---|---|
list[ActionHandler]
|
list[ActionHandler]: The actions, ready for |
Raises:
| Type | Description |
|---|---|
ValueError
|
When the simulator has no |
DANGEROUS_TRANSITIONS
module-attribute
¶
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
¶
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
¶
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: |
PrincipalT
|
session payload. Typically a :class: |
Raises:
| Type | Description |
|---|---|
AdminAuthError
|
On any rejection (unknown user, wrong password, not an admin, disabled account). |
load_principal
abstractmethod
async
¶
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: |
required |
Returns:
| Type | Description |
|---|---|
PrincipalT | None
|
PrincipalT | None: The reloaded principal, or |
PrincipalT | None
|
it no longer exists or no longer has admin access. |
principal_id
abstractmethod
¶
Return a stable identifier for the authenticated principal.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
principal
|
PrincipalT
|
The value returned by
:meth: |
required |
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The identifier serialized into the session cookie. |
display_name
¶
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
¶
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
|
|
load_account
async
¶
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 |
is_admin_identity
async
¶
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
|
|
credential_fingerprint
¶
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 |
mfa_enabled
¶
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
|
|
verify_mfa
¶
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
|
|
claim_mfa_step
async
¶
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
|
|
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: |
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 |
False
|
Raises:
| Type | Description |
|---|---|
TypeError
|
When |
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
|
|
bool
|
|
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: |
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 |
is_admin_account
¶
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
|
|
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 |
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 |
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
|
|
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
|
|
Raises:
| Type | Description |
|---|---|
ImportError
|
When the |
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
|
|
bool
|
that had not been accepted before, now recorded. |
Raises:
| Type | Description |
|---|---|
ImportError
|
When the |
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 (whenshow_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 withschema=answers its input form first.GET/POST {prefix}/m/{slug}/new— create form + submit (whencan_create).GET {prefix}/m/{slug}/{identity}— detail view.GET/POST {prefix}/m/{slug}/{identity}/edit— edit form + submit (whencan_edit).POST {prefix}/m/{slug}/{identity}/delete— delete row (whencan_delete).GET/POST {prefix}/m/{slug}/{identity}/impersonate— confirm and enter the app as the row (whenAdminModel(impersonate=...)).GET {prefix}/m/{slug}/{identity}/restore/{entry_id}— the edit form pre-filled with the values an audit entry replaced (whenaudit_modelandcan_edit).GET {prefix}/search— global search across every model withsearch_fields.- Static files under
{prefix}/staticnamedadmin_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'
|
session_store
|
SessionStore | None
|
Override the default
:class: |
None
|
cookie_secure
|
bool
|
Set the |
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
|
show_logs
|
bool
|
When |
False
|
log_dir
|
str | Path
|
Directory holding the structured log
files, matching the |
'logs'
|
access_policy
|
AdminAccessPolicy | None
|
Optional granular RBAC
hook asked |
None
|
action_policy
|
AdminActionPolicy | None
|
Hook asked
|
None
|
surface_policy
|
AdminSurfacePolicy | None
|
Hook asked
|
None
|
sql_shell
|
SqlShellService | None
|
When given, mounts the SQL
console at |
None
|
tasks
|
TaskPanelService[Any] | None
|
When given, mounts the task
panel at |
None
|
storage
|
StorageBrowserService | None
|
When given, mounts the
storage browser at |
None
|
mfa_throttle
|
AttemptThrottle | None
|
Failure budget for the
|
None
|
login_throttle
|
AttemptThrottle | Literal[False] | None
|
Failure
budget for |
None
|
login_ip_throttle
|
AttemptThrottle | Literal[False] | None
|
Failure budget for |
None
|
trusted_ip_header
|
str | None
|
Single edge-set header holding the
real client IP (e.g. |
None
|
session_revocations
|
AdminSessionRevocations | None
|
Where
|
None
|
search_results_per_model
|
int
|
Rows the global search lists per
model. Defaults to :data: |
ADMIN_SEARCH_RESULTS_PER_MODEL
|
Returns:
| Name | Type | Description |
|---|---|---|
APIRouter |
APIRouter
|
A router ready to attach via |
Raises:
| Type | Description |
|---|---|
ImportError
|
When the |
ValueError
|
When |
ADMIN_SEARCH_RESULTS_PER_MODEL
module-attribute
¶
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
¶
Longest global-search term, in characters, that runs a query.
ADMIN_SEARCH_MAX_TERMS
module-attribute
¶
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.
|
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 |
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: |
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
|
|
session_id |
str
|
Random id of this session, the handle
:class: |
credential_digest |
str
|
:func: |
to_payload
¶
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 |
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 |
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
|
|
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 |
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
¶
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
|
|
bool
|
|
|
bool
|
data: |
admin_credential_digest
¶
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: |
required |
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
32 hex characters, or |
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'
|
max_age_seconds
|
int
|
Session lifetime; cookies older than
this are rejected by :meth: |
ADMIN_SESSION_MAX_AGE_SECONDS
|
secure
|
bool
|
Whether to flag the cookie |
True
|
same_site
|
SameSite
|
|
'lax'
|
path
|
str
|
Cookie path. Defaults to |
'/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 |
True
|
same_site
|
SameSite
|
|
'lax'
|
path
|
str
|
Cookie path scope. |
'/admin'
|
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
ImportError
|
When the |
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 |
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
¶
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: |
required |
secure
|
bool
|
Whether to flag the cookie |
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 |
ImportError
|
When the |
current
¶
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 |
str | None
|
expired or tampered with. |
issue
¶
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
¶
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
¶
Check the submitted field against the cookie, in constant time.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
request
|
Request
|
The inbound request. |
required |
submitted
|
str
|
The |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
|
clear
¶
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 — |
dangerous |
bool
|
When |
schema |
type[BaseModel] | None
|
The input the operator fills in
before the action runs; |
AdminAuthError
¶
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
¶
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
¶
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: |
where |
Callable[[], ColumnElement[bool]] | None
|
Builds an extra
filter for every count ( |
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 ( |
slug |
str
|
The URL segment, derived from |
Raises:
| Type | Description |
|---|---|
TypeError
|
When |
ValueError
|
When |
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: |
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]: |
dict[str, Any]
|
|
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 ( |
accent_hover |
str
|
Hover/active shade of :attr: |
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_fg |
str | None
|
Text color on the header and sidebar.
|
page_bg |
str | None
|
Main content background. |
radius |
str
|
Border-radius applied to buttons, inputs, cards
and tables ( |
font_family |
str | None
|
CSS |
logo_url |
str | None
|
URL of an image shown in the header
instead of the brand text. |
logo_alt |
str
|
|
favicon_url |
str | None
|
URL of the browser-tab favicon.
|
footer_text |
str
|
Text shown in the page footer. |
dark_mode |
bool
|
When |
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
¶
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
¶
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 |
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.