Ir para o conteúdo

tempest_fastapi_sdk.services, tempest_fastapi_sdk.controllers

As classes base da camada de serviço e de controller, e o mixin de serviço com arquivo armazenado.

« Admin, dados e API


BaseService

BaseService(repository: RepositoryT)

Bases: Generic[RepositoryT, ResponseT, UpdateT, PrimaryKeyT]

Thin business-logic layer wrapping a :class:BaseRepository.

The default implementation exposes CRUD pass-through methods that delegate to the repository and apply map_to_response so the surface matches what routers/controllers consume. Concrete services should override methods that involve orchestration (multi-repository writes, external side effects, domain rules); pure pass-through methods can be left untouched.

When the concrete repository declares its response schema (BaseRepository[Model, ResponseSchema]), the mapping methods require ResponseT to agree with that schema instead of relying on unchecked Any propagation.

Generic parameters

RepositoryT: The concrete repository class. ResponseT: The response schema returned by the service. UpdateT: The update-payload schema accepted by :meth:update. Optional — defaults to :class:BaseSchema, so a two-argument BaseService[Repo, Resp] still works; supply it (BaseService[Repo, Resp, MyUpdateSchema]) to type the update payload precisely. PrimaryKeyT: Primary-key type accepted by :meth:get_by_id, :meth:update and :meth:delete. Optional — defaults to UUID, so existing two- and three-argument declarations stay compatible; pass BaseService[Repo, Resp, Update, int] for an integer-keyed entity.

Attributes:

Name Type Description
repository RepositoryT

The repository the service delegates to.

Initialize the service.

Parameters:

Name Type Description Default
repository RepositoryT

The repository to delegate to.

required

get_by_id async

get_by_id(id: PrimaryKeyT) -> ResponseT

Fetch a single record by primary key and map it to a response.

Parameters:

Name Type Description Default
id PrimaryKeyT

The primary key.

required

Returns:

Name Type Description
ResponseT ResponseT

The mapped response.

Raises:

Type Description
AppException

repository.not_found_exception when no record matches.

get_or_none async

get_or_none(filters: dict[str, Any]) -> ResponseT | None

Return the matching record (mapped) or None.

Parameters:

Name Type Description Default
filters dict[str, Any]

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

required

Returns:

Type Description
ResponseT | None

ResponseT | None: The mapped response, or None.

list async

list(
    filters: dict[str, Any] | None = None,
    order_by: Any | None = None,
    ascending: bool = True,
) -> list[ResponseT]

Return every matching record mapped to a response.

Returns [] when nothing matches, in line with the SDK collection convention (never raises *NotFoundError for empty result sets).

Parameters:

Name Type Description Default
filters dict[str, Any] | None

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

None
order_by Any | None

A SQLAlchemy column expression to order by.

None
ascending bool

Whether to order ascending.

True

Returns:

Type Description
list[ResponseT]

list[ResponseT]: The mapped responses.

paginate async

paginate(
    filters: dict[str, Any] | None = None,
    order_by: str | None = None,
    page: int = 1,
    page_size: int = 20,
    ascending: bool = True,
) -> dict[str, Any]

Return an offset page with items mapped to responses.

Parameters:

Name Type Description Default
filters dict[str, Any] | None

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

None
order_by str | None

Column name to order by.

None
page int

1-indexed page number.

1
page_size int

Items per page.

20
ascending bool

Whether to order ascending.

True

Returns:

Type Description
dict[str, Any]

dict[str, Any]: Mapping with items (mapped),

dict[str, Any]

total, page, size and pages.

count async

count(filters: dict[str, Any] | None = None) -> int

Count the rows matching filters.

Parameters:

Name Type Description Default
filters dict[str, Any] | None

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

None

Returns:

Name Type Description
int int

The matching row count.

exists async

exists(filters: dict[str, Any]) -> bool

Whether at least one row matches filters.

Parameters:

Name Type Description Default
filters dict[str, Any]

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

required

Returns:

Name Type Description
bool bool

True if at least one row matches.

update async

update(id: PrimaryKeyT, data: UpdateT) -> ResponseT

Apply a partial update to a record and map it to a response.

Fetches the row by primary key, copies the fields present in data onto the instance, persists, and returns the mapped response. Because :meth:BaseSchema.to_dict drops unset and None fields, only the values the caller actually supplied are applied — so the same method serves both full (PUT) and partial (PATCH) updates.

Override this in a concrete service when an update needs orchestration (cross-repository writes, domain rules, side effects); leave it untouched for plain field copies.

Parameters:

Name Type Description Default
id PrimaryKeyT

The primary key of the record to update.

required
data UpdateT

The update payload (a :class:BaseSchema). Fields left unset (or None) are not applied.

required

Returns:

Name Type Description
ResponseT ResponseT

The mapped, updated response.

Raises:

Type Description
AppException

repository.not_found_exception when no record with id exists.

ConflictException

On integrity violations while persisting.

delete async

delete(id: PrimaryKeyT) -> None

Delete a row by primary key.

Parameters:

Name Type Description Default
id PrimaryKeyT

The primary key.

required

Raises:

Type Description
AppException

repository.not_found_exception when no record with id exists.

StoredFileServiceMixin

Bases: Generic[ModelType, PrimaryKeyT]

Manage a single object-storage key field on a service's model.

Mix into a service that already owns a repository (e.g. a :class:tempest_fastapi_sdk.BaseService subclass) and exposes an upload_utils and a storage collaborator::

class UserService(
    BaseService[UserRepository, UserResponseSchema],
    StoredFileServiceMixin[UserModel],
):
    def __init__(self, repository, storage, upload_utils):
        super().__init__(repository)
        self.storage = storage
        self.upload_utils = upload_utils

user = await service.set_file(
    user, image, field="profile_picture", subdir="profiles"
)
url = await service.file_url(user.profile_picture)

The mixin does not construct its collaborators — it reads them off self so the owning service stays in charge of configuration (size limits, allowed types, bucket).

Generic parameters

ModelType: The ORM model whose field is managed (:class:~tempest_fastapi_sdk.db.RepositoryModelProtocol). PrimaryKeyT: Optional primary-key type accepted by :meth:set_file and :meth:clear_file alongside ModelType. Defaults to UUID, so StoredFileServiceMixin[UserModel] stays compatible; pass StoredFileServiceMixin[OrderModel, int] for an integer-keyed model.

Attributes:

Name Type Description
repository BaseRepository[ModelType, Any, PrimaryKeyT]

Supplied by the service.

upload_utils SupportsUpload

Supplied by the service.

storage SupportsPresign

Supplied by the service.

set_file async

set_file(
    ref: PrimaryKeyT | ModelType,
    file: UploadFile,
    *,
    field: str,
    subdir: str = "",
    filename: str | None = None,
    keep_original_name: bool = False,
) -> ModelType

Upload file and store its key on field, replacing any old one.

The new object is written before the old one is deleted (via :meth:SupportsUpload.replace), so a failed upload leaves the existing file untouched. The entity is re-resolved on the repository's session first, so a detached instance (e.g. the authenticated user) is safely re-attached before the write.

Parameters:

Name Type Description Default
ref PrimaryKeyT | ModelType

The entity to update, by id or instance.

required
file UploadFile

The uploaded file.

required
field str

Name of the model attribute holding the storage key.

required
subdir str

Optional key prefix / sub-directory.

''
filename str | None

Explicit final filename. When omitted the upload helper derives one.

None
keep_original_name bool

Preserve the upload's original filename when filename is not given.

False

Returns:

Name Type Description
ModelType ModelType

The persisted entity with the new key on field.

Raises:

Type Description
AppException

repository.not_found_exception when ref is an id with no matching row.

clear_file async

clear_file(ref: PrimaryKeyT | ModelType, *, field: str) -> ModelType

Delete the stored object (if any) and null field.

A no-op write is avoided when the field is already empty: the resolved entity is returned without a commit.

Parameters:

Name Type Description Default
ref PrimaryKeyT | ModelType

The entity to update, by id or instance.

required
field str

Name of the model attribute holding the storage key.

required

Returns:

Name Type Description
ModelType ModelType

The entity with field set to None (persisted

ModelType

only when there was a key to clear).

Raises:

Type Description
AppException

repository.not_found_exception when ref is an id with no matching row.

file_url async

file_url(key: str | None, *, expires: timedelta = _DEFAULT_URL_TTL) -> str | None

Return a presigned download URL for key, or None when empty.

Parameters:

Name Type Description Default
key str | None

The stored object key (typically the field value). None / empty returns None so callers can forward the result straight into a response schema.

required
expires timedelta

URL lifetime. Defaults to one hour.

_DEFAULT_URL_TTL

Returns:

Type Description
str | None

str | None: A temporary download URL, or None when there is

str | None

no key.

file_urls async

file_urls(
    keys: Iterable[str | None],
    *,
    expires: timedelta = _DEFAULT_URL_TTL,
    max_concurrency: int = 16,
) -> dict[str, str]

Return presigned download URLs for many keys at once.

The batch counterpart of :meth:file_url for list endpoints that must resolve one stored key per row (e.g. a page of profiles). Presigning is dispatched concurrently by the storage client, so a page of N rows costs one bounded fan-out instead of N sequential round-trips. Empty / None keys are dropped and duplicates are collapsed, so the result holds one entry per distinct non-empty key — look each row's URL up with result.get(row.key), which yields None for a row whose key was empty.

Parameters:

Name Type Description Default
keys Iterable[str | None]

The stored object keys, typically one field value per row. None / empty entries are skipped.

required
expires timedelta

URL lifetime for every key. Defaults to one hour.

_DEFAULT_URL_TTL
max_concurrency int

Maximum signings awaited at once.

16

Returns:

Type Description
dict[str, str]

dict[str, str]: Mapping of each distinct non-empty key to its

dict[str, str]

presigned download URL.

Controller

Root of the controller layer, for controllers that orchestrate.

Subclass it when a controller coordinates several services — under one lock, one commit, one audit entry — and has no CRUD of a single resource to pass through. It ships no methods on purpose: inheriting :class:BaseController there would hand the router get_by_id, update and delete methods that mean nothing for that controller.

What it fixes is the convention of the layer, the same one :class:BaseController follows:

  • services are injected through __init__ (built by a FastAPI dependency provider, never inside the controller);
  • the controller never touches the database — no session, no repository, no engine. Persistence goes through the services it receives.

The convention is not checked at runtime: the constructor belongs to the subclass, and telling a service from a repository by annotation would need the subclass's forward references resolved.

Examples:

>>> from tempest_fastapi_sdk import Controller
>>> class BillingController(Controller):
...     def __init__(self, invoices: object, ledger: object) -> None:
...         self.invoices: object = invoices
...         self.ledger: object = ledger
>>> isinstance(BillingController(object(), object()), Controller)
True

BaseController

BaseController(service: ServiceT)

Bases: Controller, Generic[ServiceT, ResponseT, UpdateT, PrimaryKeyT]

Thin orchestration layer between routers and one CRUD service.

The CRUD specialization of :class:Controller: it takes a single service and passes its CRUD methods through. For a controller that orchestrates several services without single-resource CRUD, subclass :class:Controller instead.

Following the SDK layering rules (router → controller → service → repository), controllers are kept present even when no orchestration is required so the import graph stays uniform. Override methods here when a single endpoint needs to call multiple services or apply cross-cutting policy; leave the pass-throughs untouched otherwise.

Generic parameters

ServiceT: The concrete service class. Pass-through methods derive their response and update types from ServiceT, so BaseController[Service] is enough when the primary key is UUID. ResponseT: Optional, defaults to Any so existing BaseController[Service, Resp] declarations keep working. Pass-through return types come from ServiceT, not this parameter. UpdateT: Optional, defaults to :class:BaseSchema so existing BaseController[Service, Resp, Update] declarations keep working. :meth:update accepts ServiceT's update schema. PrimaryKeyT: Optional primary-key type accepted by :meth:get_by_id, :meth:update and :meth:delete. Defaults to UUID so existing one-, two- and three-argument declarations keep working; pass BaseController[Service, Resp, Update, int] for an integer-keyed service.

Attributes:

Name Type Description
service ServiceT

The service the controller delegates to.

Initialize the controller.

Parameters:

Name Type Description Default
service ServiceT

The service to delegate to.

required

get_by_id async

get_by_id(id: PrimaryKeyT) -> _ServiceResponseT

Pass-through to :meth:BaseService.get_by_id.

Parameters:

Name Type Description Default
id PrimaryKeyT

The primary key.

required

Returns:

Name Type Description
_ServiceResponseT _ServiceResponseT

The mapped response returned by self.service.

list async

list(
    filters: dict[str, Any] | None = None,
    order_by: Any | None = None,
    ascending: bool = True,
) -> list[_ServiceResponseT]

Pass-through to :meth:BaseService.list.

Parameters:

Name Type Description Default
filters dict[str, Any] | None

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

None
order_by Any | None

A SQLAlchemy column expression.

None
ascending bool

Whether to order ascending.

True

Returns:

Type Description
list[_ServiceResponseT]

list[_ServiceResponseT]: The mapped responses returned by

list[_ServiceResponseT]

self.service.

paginate async

paginate(
    filters: dict[str, Any] | None = None,
    order_by: str | None = None,
    page: int = 1,
    page_size: int = 20,
    ascending: bool = True,
) -> dict[str, Any]

Pass-through to :meth:BaseService.paginate.

Parameters:

Name Type Description Default
filters dict[str, Any] | None

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

None
order_by str | None

Column name to order by.

None
page int

1-indexed page number.

1
page_size int

Items per page.

20
ascending bool

Whether to order ascending.

True

Returns:

Type Description
dict[str, Any]

dict[str, Any]: The paginated payload.

count async

count(filters: dict[str, Any] | None = None) -> int

Pass-through to :meth:BaseService.count.

Parameters:

Name Type Description Default
filters dict[str, Any] | None

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

None

Returns:

Name Type Description
int int

The matching row count.

update async

update(id: PrimaryKeyT, data: _ServiceUpdateT) -> _ServiceResponseT

Pass-through to :meth:BaseService.update.

Parameters:

Name Type Description Default
id PrimaryKeyT

The primary key of the record to update.

required
data _ServiceUpdateT

The update payload accepted by self.service (unset fields skipped).

required

Returns:

Name Type Description
_ServiceResponseT _ServiceResponseT

The mapped, updated response returned by

_ServiceResponseT

self.service.

delete async

delete(id: PrimaryKeyT) -> None

Pass-through to :meth:BaseService.delete.

Parameters:

Name Type Description Default
id PrimaryKeyT

The primary key.

required

SupportsPresign

Bases: Protocol

Structural type for the storage client the mixin needs.

Satisfied by :class:tempest_fastapi_sdk.AsyncMinIOClient.

presigned_get_url async

presigned_get_url(key: str, *, expires: timedelta = ...) -> str

Return a temporary download URL for key.

Parameters:

Name Type Description Default
key str

Stored object key.

required
expires timedelta

How long the signed URL stays valid.

...

Returns:

Name Type Description
str str

The signed URL.

presigned_get_urls async

presigned_get_urls(
    keys: Iterable[str], *, expires: timedelta = ..., max_concurrency: int = ...
) -> dict[str, str]

Return presigned download URLs for many keys, keyed by key.

Parameters:

Name Type Description Default
keys Iterable[str]

Stored object keys.

required
expires timedelta

How long the signed URL stays valid.

...
max_concurrency int

How many operations to run at once.

...

Returns:

Type Description
dict[str, str]

dict[str, str]: One signed URL per requested key.

SupportsUpload

Bases: Protocol

Structural type for the upload helper the mixin needs.

Satisfied by :class:tempest_fastapi_sdk.UploadUtils.

replace async

replace(
    old_key: Path | str | None,
    file: UploadFile,
    *,
    subdir: str = ...,
    filename: str | None = ...,
    keep_original_name: bool = ...,
) -> Path

Persist file and delete the object at old_key.

Parameters:

Name Type Description Default
old_key Path | str | None

Previous object to delete after a successful write.

required
file UploadFile

The uploaded file.

required
subdir str

Destination subdirectory.

...
filename str | None

Override the stored name; None derives one.

...
keep_original_name bool

Whether to keep the client-provided name.

...

Returns:

Name Type Description
Path Path

The local path written.

delete async

delete(key: Path | str) -> bool

Delete the object at key; return whether it existed.

Parameters:

Name Type Description Default
key Path | str

Stored object key.

required

Returns:

Name Type Description
bool bool

Whether the object was removed.