tempest_fastapi_sdk.utils¶
Utilitários: validação BR, senha, HTTP client, retry, upload, datas e formatação.
LocalUploadStorage
¶
Disk-backed :class:UploadStorage using aiofiles.
Writes chunks under base_dir and refuses keys that resolve
outside the base — same path-traversal protection
:class:UploadUtils already applied. The base_dir is
created (with parents) on instantiation.
Initialize.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
base_dir
|
Path | str
|
Root directory for all writes. |
required |
Raises:
| Type | Description |
|---|---|
ImportError
|
When the |
local_path
¶
Return where key lives on disk, refusing a key that escapes.
What a download route serves the file from, since a local disk
cannot mint a URL (:meth:presigned_url is always None).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
Storage key. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
Path |
Path
|
The resolved path under |
Raises:
| Type | Description |
|---|---|
InvalidFileTypeException
|
When |
write_stream
async
¶
write_stream(
key: str,
chunks: AsyncIterator[bytes],
*,
content_type: str = "application/octet-stream",
metadata: dict[str, str] | None = None,
max_size_bytes: int | None = None,
validator: ContentValidator | None = None,
) -> UploadResult
Persist chunks to base_dir / key.
content_type and metadata are accepted for protocol
parity but ignored — the local filesystem has nowhere to
store them.
Notes
content_type and metadata are accepted for
interface parity and discarded: a local filesystem backend
has nowhere to store them.
Raises:
| Type | Description |
|---|---|
InvalidFileTypeException
|
When the sniffed MIME type is not in the allowed set. |
FileTooLargeException
|
When the stream exceeds the configured maximum size. |
presigned_url
async
¶
Local storage cannot mint URLs — always None.
MinIOUploadStorage
¶
MinIOUploadStorage(client: AsyncMinIOClient, *, bucket: str | None = None)
:class:UploadStorage backed by :class:AsyncMinIOClient.
Reuses an existing client instance — typically the one wired
on the FastAPI app — so the connection pool is shared. The
bucket falls back to the client's default_bucket.
Initialize.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
client
|
AsyncMinIOClient
|
A configured MinIO client. |
required |
bucket
|
str | None
|
Target bucket. |
None
|
write_stream
async
¶
write_stream(
key: str,
chunks: AsyncIterator[bytes],
*,
content_type: str = "application/octet-stream",
metadata: dict[str, str] | None = None,
max_size_bytes: int | None = None,
validator: ContentValidator | None = None,
) -> UploadResult
Buffer chunks, validate, then put_object.
S3 needs the content length upfront, so the stream is
materialized in memory before the upload starts. For
very large objects, prefer presigned_put_url and let
the client upload directly.
presigned_url
async
¶
Return a presigned GET URL.
HTTPClient
¶
HTTPClient(
*,
base_url: str = "",
timeout: float = 10.0,
retry_policy: RetryPolicy | None = None,
failure_threshold: int = 5,
recovery_seconds: float = 30.0,
default_headers: Mapping[str, str] | None = None,
verify_tls: bool = True,
propagate_request_id: bool = True,
request_id_header: str = REQUEST_ID_HEADER,
transport: AsyncBaseTransport | None = None,
)
Async HTTP client with retries, circuit-breaker and request-id propagation.
Example:
>>> client = HTTPClient(base_url="https://api.example.com")
>>> async with client:
... response = await client.get("/users/me")
... payload: dict[str, Any] = response.json()
The client is safe to share across requests on the same
event loop — internally each call uses the shared
:class:httpx.AsyncClient connection pool.
Initialize.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
base_url
|
str
|
Prepended to relative paths. Use empty string to require absolute URLs at the call site. |
''
|
timeout
|
float
|
Per-request timeout in seconds. Overridable per call. |
10.0
|
retry_policy
|
RetryPolicy | None
|
Retry configuration.
|
None
|
failure_threshold
|
int
|
Consecutive 5xx/network errors
that trip the circuit per host. |
5
|
recovery_seconds
|
float
|
Seconds the breaker stays open before allowing one half-open probe. |
30.0
|
default_headers
|
Mapping[str, str] | None
|
Headers
attached to every request (e.g. |
None
|
verify_tls
|
bool
|
Whether to verify TLS certificates.
Default |
True
|
propagate_request_id
|
bool
|
When |
True
|
request_id_header
|
str
|
Header name the propagated id is
sent under. Defaults to :data: |
REQUEST_ID_HEADER
|
transport
|
AsyncBaseTransport | None
|
Explicit
transport for the underlying client — pass an
|
None
|
Raises:
| Type | Description |
|---|---|
ImportError
|
When the |
ValueError
|
When |
request
async
¶
request(
method: str,
url: str,
*,
params: Mapping[str, Any] | None = None,
json: object = None,
data: HTTPRequestData | None = None,
content: HTTPRequestContent | None = None,
files: HTTPRequestFiles | None = None,
headers: Mapping[str, str] | None = None,
timeout: float | None = None,
) -> Response
Perform an HTTP request with retries and circuit-breaker.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
method
|
str
|
HTTP verb ( |
required |
url
|
str
|
Absolute URL or path relative to |
required |
params
|
Mapping[str, Any] | None
|
Query-string params. |
None
|
json
|
object
|
JSON-serializable body. Mutually exclusive
with |
None
|
data
|
HTTPRequestData | None
|
Form fields. Alone it is sent
|
None
|
content
|
HTTPRequestContent | None
|
Raw body — |
None
|
files
|
HTTPRequestFiles | None
|
Multipart file parts, in any
shape httpx accepts: |
None
|
headers
|
Mapping[str, str] | None
|
Per-request headers
merged on top of |
None
|
timeout
|
float | None
|
Override for this call. |
None
|
Returns:
| Type | Description |
|---|---|
Response
|
httpx.Response: The successful response. Caller checks |
Response
|
|
Response
|
not retried). |
Raises:
| Type | Description |
|---|---|
CircuitOpenError
|
When the per-host breaker is open. |
HTTPError
|
When all attempts failed (last exception is re-raised). |
Notes
The trailing raise is defensive only: the retry loop either returns a response or raises, so it should never be reached.
A body that cannot be replayed is not retried. Retrying
re-sends the same arguments, and a stream handed to
content or files is already drained by then, so
attempt two would upload a truncated body that the server
has no way to tell from a short file. Pass bytes to keep
the retries.
get
async
¶
Shortcut for request("GET", url, ...).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url
|
str
|
Absolute URL, or a path resolved against |
required |
**kwargs
|
Any
|
Extra arguments forwarded to httpx. |
{}
|
Returns:
| Type | Description |
|---|---|
Response
|
httpx.Response: The server's response. |
post
async
¶
Shortcut for request("POST", url, ...).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url
|
str
|
Absolute URL, or a path resolved against |
required |
**kwargs
|
Any
|
Extra arguments forwarded to httpx. |
{}
|
Returns:
| Type | Description |
|---|---|
Response
|
httpx.Response: The server's response. |
put
async
¶
Shortcut for request("PUT", url, ...).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url
|
str
|
Absolute URL, or a path resolved against |
required |
**kwargs
|
Any
|
Extra arguments forwarded to httpx. |
{}
|
Returns:
| Type | Description |
|---|---|
Response
|
httpx.Response: The server's response. |
patch
async
¶
Shortcut for request("PATCH", url, ...).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url
|
str
|
Absolute URL, or a path resolved against |
required |
**kwargs
|
Any
|
Extra arguments forwarded to httpx. |
{}
|
Returns:
| Type | Description |
|---|---|
Response
|
httpx.Response: The server's response. |
delete
async
¶
Shortcut for request("DELETE", url, ...).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url
|
str
|
Absolute URL, or a path resolved against |
required |
**kwargs
|
Any
|
Extra arguments forwarded to httpx. |
{}
|
Returns:
| Type | Description |
|---|---|
Response
|
httpx.Response: The server's response. |
stream
async
¶
stream(
method: str,
url: str,
*,
params: Mapping[str, Any] | None = None,
json: object = None,
data: HTTPRequestData | None = None,
content: HTTPRequestContent | None = None,
files: HTTPRequestFiles | None = None,
headers: Mapping[str, str] | None = None,
timeout: float | None = None,
) -> AsyncGenerator[str, None]
Stream a response body line by line (e.g. NDJSON).
Retries and the circuit-breaker cover only opening the stream —
network errors and retryable statuses on the initial response are
retried with the same backoff as :meth:request. Once the first line
is yielded the connection is committed, so a mid-stream failure
(including a ReadTimeout between two chunks) propagates to the
caller instead of re-sending the request and replaying lines the
caller already consumed. A non-success status that is not going to be
retried raises httpx.HTTPStatusError before any line is yielded, so
the caller never has to inspect status_code on a stream; its body
is read first, so exc.response.content carries the server's
message (a failure reading that body is swallowed, so it never turns
the status error into a retry). Closing the generator early -- a
break, a client that disconnects -- closes the connection right
away rather than at garbage collection.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
method
|
str
|
HTTP verb. |
required |
url
|
str
|
Absolute URL or path relative to |
required |
params
|
Mapping[str, Any] | None
|
Query-string params. |
None
|
json
|
object
|
JSON-serializable body. |
None
|
data
|
HTTPRequestData | None
|
Form body. |
None
|
content
|
HTTPRequestContent | None
|
Raw body. |
None
|
files
|
HTTPRequestFiles | None
|
Multipart files. |
None
|
headers
|
Mapping[str, str] | None
|
Per-request headers merged on
top of the defaults + propagated |
None
|
timeout
|
float | None
|
Override for this call. |
None
|
Yields:
| Name | Type | Description |
|---|---|---|
str |
AsyncGenerator[str, None]
|
Decoded response lines, in order (empty lines included — the |
AsyncGenerator[str, None]
|
caller skips them). |
Raises:
| Type | Description |
|---|---|
CircuitOpenError
|
When the per-host breaker is open. |
HTTPStatusError
|
When the (final) response status is not a success and is not retried. |
HTTPError
|
When every open attempt failed with a network error (the last exception is re-raised). |
stream_bytes
async
¶
stream_bytes(
method: str,
url: str,
*,
params: Mapping[str, Any] | None = None,
json: object = None,
data: HTTPRequestData | None = None,
content: HTTPRequestContent | None = None,
files: HTTPRequestFiles | None = None,
headers: Mapping[str, str] | None = None,
timeout: float | None = None,
) -> AsyncGenerator[bytes, None]
Stream a response body as raw byte chunks (audio, files).
The same retry, circuit-breaker and error contract as :meth:stream
-- retries only while opening, the connection committed once the
first chunk is yielded -- for a body that is not text: a WAV or PCM
stream, a file download. Chunks arrive as the server flushes them.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
method
|
str
|
HTTP verb. |
required |
url
|
str
|
Absolute URL or path relative to |
required |
params
|
Mapping[str, Any] | None
|
Query-string params. |
None
|
json
|
object
|
JSON-serializable body. |
None
|
data
|
HTTPRequestData | None
|
Form body. |
None
|
content
|
HTTPRequestContent | None
|
Raw body. |
None
|
files
|
HTTPRequestFiles | None
|
Multipart files. |
None
|
headers
|
Mapping[str, str] | None
|
Per-request headers. |
None
|
timeout
|
float | None
|
Override for this call. |
None
|
Yields:
| Name | Type | Description |
|---|---|---|
bytes |
AsyncGenerator[bytes, None]
|
The body, chunk by chunk, in order. |
Raises:
| Type | Description |
|---|---|
CircuitOpenError
|
When the per-host breaker is open. |
HTTPStatusError
|
When the (final) response status is not a
success and is not retried; |
HTTPError
|
When every open attempt failed with a network error. |
HTTPFileContent
module-attribute
¶
One file payload accepted inside :data:HTTPRequestFiles.
HTTPFilePart
module-attribute
¶
HTTPFilePart = (
HTTPFileContent
| tuple[str | None, HTTPFileContent]
| tuple[str | None, HTTPFileContent, str | None]
| tuple[str | None, HTTPFileContent, str | None, Mapping[str, str]]
)
One multipart file entry in any tuple shape httpx accepts.
HTTPRequestContent
module-attribute
¶
Raw body accepted by :meth:HTTPClient.request and streaming helpers.
HTTPRequestData
module-attribute
¶
Form fields accepted by :meth:HTTPClient.request and streaming helpers.
HTTPRequestFiles
module-attribute
¶
HTTPRequestFiles = Mapping[str, HTTPFilePart] | Sequence[tuple[str, HTTPFilePart]]
Multipart file parts accepted by :meth:HTTPClient.request and streaming helpers.
CircuitOpenError
¶
Bases: Exception
Raised when the circuit-breaker rejects a call.
Carries the host that tripped the breaker so callers can branch on it (e.g. fall back to a cache or a queue).
Initialize.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
host
|
str
|
The host whose breaker is open. |
required |
RetryLogger
¶
Bases: Protocol
The two calls :func:async_retry makes on whatever it logs to.
async_retry writes exactly one WARNING per retry and one ERROR
when the budget runs out. Typing the parameter as
logging.Logger named the implementation the SDK happens to
use rather than that requirement — and excluded
:class:~tempest_fastapi_sdk.LogUtils, which is the logger this
same SDK hands the service. A module that opens with
logger: LogUtils = LogUtils(__name__) could not pass that
logger to a decorator shipped alongside it: the call worked at
runtime, because the shapes match, and failed under mypy with
Argument "logger" to "async_retry" has incompatible type
"LogUtils". The workaround, logger=logger.logger, reaches
past the facade to the object it wraps.
Both parameters are positional-only. A protocol member written
def warning(self, msg: str) also demands the name msg
from the implementer, and the two loggers disagree —
logging.Logger calls it msg, LogUtils calls it
message. mypy accepts either spelling; basedpyright rejects the
mismatch outright, which is the checker the consumer runs.
runtime_checkable makes isinstance work, but it only checks
that the two members exist — the signatures are the type
checker's job, and the recipe carries a typed example so both
checkers see it.
warning
¶
Emit a WARNING record.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
msg
|
str
|
The |
required |
*args
|
object
|
Interpolation arguments, kept lazy. |
()
|
error
¶
Emit an ERROR record.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
msg
|
str
|
The |
required |
*args
|
object
|
Interpolation arguments, kept lazy. |
()
|
RetryPolicy
dataclass
¶
RetryPolicy(
max_attempts: int = 3,
backoff_initial_seconds: float = 0.5,
backoff_max_seconds: float = 8.0,
retry_statuses: frozenset[int] = (lambda: frozenset({429, 500, 502, 503, 504}))(),
retry_on_read_timeout: bool = True,
)
Bounded exponential backoff for retried operations.
The first retry sleeps for backoff_initial_seconds; each
subsequent retry doubles the wait, capped at
backoff_max_seconds. Total retries are bounded by
max_attempts (the first try counts).
Attributes:
| Name | Type | Description |
|---|---|---|
max_attempts |
int
|
Total tries including the first.
|
backoff_initial_seconds |
float
|
Sleep before the second attempt. |
backoff_max_seconds |
float
|
Hard cap per sleep. |
retry_statuses |
frozenset[int]
|
HTTP status codes worth
retrying. Defaults to common 5xx; |
retry_on_read_timeout |
bool
|
Whether
:class: |
sleep_for
¶
Compute the sleep between attempt n and attempt n+1.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
attempt
|
int
|
Zero-based retry attempt number. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
float |
float
|
Seconds to wait before the next attempt. |
async_retry
¶
async_retry(
policy: RetryPolicy | None = None,
exceptions: tuple[type[BaseException], ...] = (Exception,),
*,
logger: RetryLogger | None = None,
) -> Callable[[Callable[P, Awaitable[T]]], Callable[P, Awaitable[T]]]
Retry an async callable with the bounded backoff of policy.
Example:
>>> from tempest_fastapi_sdk import RetryPolicy, async_retry
>>>
>>> @async_retry(RetryPolicy(max_attempts=5), (ConnectionError,))
... async def connect(url: str) -> None:
... ...
When every attempt fails, the last exception propagates rather
than a wrapper: a caller that could react to a permanent
ConnectionError should still see a ConnectionError.
exceptions defaults to Exception, which deliberately
excludes :class:asyncio.CancelledError — it derives from
BaseException, and retrying a cancelled task fights the
cancellation instead of honoring it. Narrow the tuple to the
transient failures you actually mean; a TypeError retried three
times is the same bug, later.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
policy
|
RetryPolicy | None
|
Attempt budget and backoff curve.
|
None
|
exceptions
|
tuple[type[BaseException], ...]
|
Exception types that count as transient. Anything outside the tuple propagates immediately, without consuming an attempt. |
(Exception,)
|
logger
|
RetryLogger | None
|
Where the retry and give-up
records go. Anything with |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
Callable |
Callable[[Callable[P, Awaitable[T]]], Callable[P, Awaitable[T]]]
|
A decorator wrapping the target coroutine function. |
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
form_encode
¶
Flatten a nested payload into bracket-notation form fields.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
payload
|
Mapping[str, Any] | None
|
The request body as a nested
mapping. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, str]
|
dict[str, str]: Flat |
dict[str, str]
|
|
None values are dropped rather than sent empty: on these APIs
an empty string is a real value (it clears a field), so serializing
None as "" would silently erase data the caller never meant to
touch. Empty mappings and lists disappear for the same reason — they
have no bracket path to occupy.
Examples:
PasswordUtils
¶
Hash and verify passwords using bcrypt.
Stateless utility — instantiate once and reuse across the
application. The cost factor (rounds) controls how slow
hashing is; 12 is a sensible 2026 default. Raise it when CPU
budget allows to keep up with hardware.
Attributes:
| Name | Type | Description |
|---|---|---|
rounds |
int
|
The bcrypt cost factor. |
truncate_legacy_bcrypt |
bool
|
Whether :meth: |
Initialize.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rounds
|
int
|
The bcrypt cost factor. Higher values make
hashing slower and brute-force attacks harder.
Defaults to |
12
|
truncate_legacy_bcrypt
|
bool
|
Truncate |
True
|
Raises:
| Type | Description |
|---|---|
ImportError
|
When the |
hash
¶
Hash a plaintext password.
bcrypt refuses inputs over 72 UTF-8 bytes — note bytes, not
characters, so an emoji costs four and an accented Latin letter
two. Validate the length before calling this from a request
handler, or the ValueError becomes an HTTP 500 instead of a
422; :class:~tempest_fastapi_sdk.UserAuthService does that via
AUTH_PASSWORD_MAX_BYTES. This method never truncates, even
when :attr:truncate_legacy_bcrypt is True.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
plain
|
str
|
The plaintext password. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The bcrypt hash encoded as a UTF-8 string, ready to |
str
|
persist in a database column. |
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
verify
¶
Verify a plaintext password against an existing hash.
Catches malformed hashes and returns False rather than
raising, so callers can branch on the boolean without
bcrypt-specific error handling.
When :attr:truncate_legacy_bcrypt is True (the default),
plain is UTF-8 encoded and truncated to the first 72 bytes
before calling bcrypt.checkpw. Versions of bcrypt prior
to 5.0 (and passlib) truncated inputs silently at 72 bytes;
starting with bcrypt 5.0.0, both hashpw and checkpw
raise ValueError past 72 bytes instead. Truncating on
verification keeps legacy hashes from long passphrases working
without weakening them, because bcrypt never mixed bytes beyond
the 72nd into the stored hash. :meth:hash never truncates.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
plain
|
str
|
The plaintext password to verify. |
required |
hashed
|
str
|
The previously stored bcrypt hash. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
|
dummy_verify
¶
Spend one :meth:verify against a throwaway hash, and fail.
Call it on the login branch where no stored hash exists (unknown account), so that branch pays the same bcrypt cost as a wrong password. Without it the refusal for a missing account returns before any hashing, and the response time alone tells a caller which addresses are registered.
The throwaway hash is built on first use with this instance's
:attr:rounds, the cost the instance writes for real accounts,
then cached; that first call pays one extra hash.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
plain
|
str
|
The submitted plaintext password. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
Always |
bool
|
meth: |
PasswordPolicy
dataclass
¶
The length + complexity rules a plaintext password must satisfy.
The same three numbers AuthSettings declares
(AUTH_PASSWORD_MIN_LENGTH, AUTH_PASSWORD_MAX_BYTES,
AUTH_PASSWORD_REQUIRE_COMPLEXITY), in a value object any caller
can build — so a surface that takes a password but has no settings
object of its own (the admin panel's password field) enforces the
project's real rules instead of inventing its own.
Build it from your settings with :meth:from_settings; the defaults
here mirror the AuthSettings field defaults.
Attributes:
| Name | Type | Description |
|---|---|---|
min_length |
int
|
Minimum length in characters. |
max_bytes |
int
|
Maximum length in UTF-8 bytes — the unit bcrypt counts. |
require_complexity |
bool
|
Require one lowercase, one uppercase, one digit and one non-alphanumeric character, and raise the effective length floor to at least 8. |
from_settings
classmethod
¶
from_settings(settings: PasswordSettingsLike) -> PasswordPolicy
Read the policy off an AuthSettings-shaped object.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
settings
|
PasswordSettingsLike
|
Any object carrying the three
|
required |
Returns:
| Name | Type | Description |
|---|---|---|
PasswordPolicy |
PasswordPolicy
|
The policy those settings describe. |
PasswordSettingsLike
¶
Bases: Protocol
The three settings fields :meth:PasswordPolicy.from_settings reads.
Declared as read-only properties so frozen
:class:~tempest_fastapi_sdk.settings.AuthSettings subclasses and plain
objects with ordinary attributes are both accepted.
PasswordPolicyViolation
dataclass
¶
PasswordPolicyViolation(
message: str, details: dict[str, Any], code: PasswordViolationCodeEnum
)
Why a password was rejected, in a form both callers can render.
Attributes:
| Name | Type | Description |
|---|---|---|
message |
str
|
Human-readable reason. |
details |
dict[str, Any]
|
Structured context — the bound that was crossed, or the character classes that were missing. |
code |
PasswordViolationCodeEnum
|
Which rule was broken, stable across releases and locales. |
PasswordViolationCodeEnum
¶
Bases: BaseStrEnum
Which rule of a :class:PasswordPolicy a password broke.
Stable identifiers a client can branch on and a message catalog can
translate: UserAuthService raises with the value as
message_key, and the default catalog carries all three in pt-BR
and en-US.
Attributes:
| Name | Type | Description |
|---|---|---|
PASSWORD_TOO_SHORT |
Below the effective minimum length. |
|
PASSWORD_TOO_LONG |
Above |
|
PASSWORD_TOO_WEAK |
Missing a required character class under complexity mode. |
check_password_policy
¶
check_password_policy(
password: str, policy: PasswordPolicy | None = None
) -> PasswordPolicyViolation | None
Check a plaintext password against a policy.
Returns the violation instead of raising, so a form can put the
message next to the field while a service turns the same value into
a ValidationException. That split is the reason this lives here
and not inside the auth service: the rule was private to
UserAuthService, so every other surface that accepts a password
— the admin panel's create form, a provisioning script — either
skipped it or wrote its own.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
password
|
str
|
The plaintext to check. |
required |
policy
|
PasswordPolicy | None
|
The rules to apply. |
None
|
Returns:
| Type | Description |
|---|---|
PasswordPolicyViolation | None
|
PasswordPolicyViolation | None: The first violation found, or |
PasswordPolicyViolation | None
|
|
generate_password
¶
generate_password(
*, min_length: int = 8, max_bytes: int = 72, require_complexity: bool = True
) -> str
Mint a random password that satisfies the configured policy.
For flows where nobody types a password — the OAuth callback that
creates an account, an admin provisioning a user — but the column
is still NOT NULL. The account owner reaches a password of
their own through the ordinary reset flow; this one only has to be
unguessable and accepted.
Compliance is by construction, not by retry. Drawing from one
flat alphabet and hoping is the defect this function exists to
avoid: fed to UserAuthService._enforce_password_policy with
complexity on and a 12-character floor, 200 000 samples
each, secrets.token_urlsafe(16) was rejected 53.01% of the
time, secrets.token_urlsafe(32) 26.54%, and
secrets.token_hex(32) 100% (it has neither uppercase nor a
special character, on every single draw). A generator that passes
three times in four fails intermittently, in production, inside a
callback, about a password the user never typed. So one character
is drawn from each required class first, the rest fills from their
union, and the result is shuffled with secrets.SystemRandom.
Every character is ASCII, so the returned length is also the UTF-8
byte count bcrypt measures — max_bytes needs no separate
encoding check.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
min_length
|
int
|
The policy's |
8
|
max_bytes
|
int
|
The policy's |
72
|
require_complexity
|
bool
|
The policy's
|
True
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
A fresh random password of at least |
str
|
characters and at most |
Raises:
| Type | Description |
|---|---|
ValueError
|
When the policy cannot be satisfied at all —
|
DEFAULT_GENERATED_PASSWORD_LENGTH
module-attribute
¶
Length :func:generate_password targets when the policy allows it.
Well above every default floor, and well under the 72-byte bcrypt ceiling, so the common case needs no clamping in either direction.
JWTUtils
¶
JWTUtils(
secret: str,
*,
algorithm: str = "HS256",
default_ttl: timedelta = timedelta(hours=1),
issuer: str | None = None,
)
Encode and decode JWTs using a shared secret.
Every token gets an iat (issued-at) and exp (expiry)
claim populated automatically; the caller is responsible for the
rest (sub, custom claims, etc.). When the helper is created
with issuer=, the iss claim is also added on encode and
verified on decode.
Attributes:
| Name | Type | Description |
|---|---|---|
algorithm |
str
|
The JWT signing algorithm. |
default_ttl |
timedelta
|
Default expiration applied on
:meth: |
Initialize.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
secret
|
str
|
The signing key (HMAC) or private key (RSA/EC). |
required |
algorithm
|
str
|
JWT algorithm. Defaults to |
'HS256'
|
default_ttl
|
timedelta
|
TTL applied by :meth: |
timedelta(hours=1)
|
issuer
|
str | None
|
Value for the |
None
|
Raises:
| Type | Description |
|---|---|
ImportError
|
When the |
encode
¶
Encode payload as a signed JWT.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
payload
|
dict[str, Any]
|
Claims to include. Typically
contains a stable subject ( |
required |
ttl
|
timedelta | None
|
Override :attr: |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The compact-serialized JWT. |
decode
¶
Decode and verify a JWT.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
token
|
str
|
The token to decode. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
dict[str, Any]: The decoded claims. |
Raises:
| Type | Description |
|---|---|
ExpiredTokenException
|
When the |
InvalidTokenException
|
For every other validation failure (bad signature, wrong issuer, missing claim, malformed payload, etc.). |
decode_or_none
¶
Decode and verify a JWT, returning None on failure.
Convenience wrapper for opportunistic decoding (e.g. soft auth that downgrades the user to anonymous when the token is missing/bad).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
token
|
str
|
The token to decode. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any] | None
|
dict[str, Any] | None: The decoded claims, or |
dict[str, Any] | None
|
when the token is invalid or expired. |
token_type_allowed
¶
token_type_allowed(
payload: Mapping[str, Any],
accepted: Collection[str],
*,
strict: bool = False,
legacy_claims: Collection[str] = (),
) -> bool
Return whether a decoded token's type is one of accepted.
Tokens minted by this version carry typ, so the check is a plain
membership test. Tokens minted before typ existed — or by a
project calling :meth:~tempest_fastapi_sdk.JWTUtils.encode itself —
have no typ; those pass by default, because rejecting them would
log every existing session out on upgrade. The two markers the SDK
already stamped, refresh: True and purpose: "mfa_pending", are
read as a fallback so an old refresh or MFA-pending token is still
classified instead of being waved through as an access token.
Any other purpose claim is read as the token's type too. A token
that declares what it is for — {"purpose": "password_reset"},
the shape single-use links are commonly signed with — is a
single-purpose token, never a session, so it passes only where its
purpose is listed in accepted. Before this, such a token reached
the untyped fallback and authorized every route guarded with the
default strict=False for its whole lifetime:
>>> token_type_allowed({"purpose": "password_reset"}, [ACCESS_TOKEN_TYPE])
False
>>> token_type_allowed({"purpose": "password_reset"}, ["password_reset"])
True
That default is right for tokens this SDK minted and wrong for
everyone else's. A service that already separated access from refresh
under a claim of its own — type, token_type — has no typ on
any legacy token and no SDK fallback marker either, so every one of
them would reach return True and authorize any call site for the
length of the refresh TTL. legacy_claims names where else to read
the type from, and strict refuses what stays unclassified:
>>> token_type_allowed({"type": "refresh"}, [ACCESS_TOKEN_TYPE])
True
>>> token_type_allowed(
... {"type": "refresh"},
... [ACCESS_TOKEN_TYPE],
... strict=True,
... legacy_claims=("type",),
... )
False
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
payload
|
Mapping[str, Any]
|
Decoded, signature-verified claims. |
required |
accepted
|
Collection[str]
|
Token types the call site allows. |
required |
strict
|
bool
|
Reject a payload whose type cannot be determined
instead of accepting it. Leaves the migration window closed at
the cost of logging out sessions minted before |
False
|
legacy_claims
|
Collection[str]
|
Extra claim names to read the
type from, in order, when |
()
|
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
|
token_amr
¶
Return the amr methods of a decoded token.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
payload
|
Mapping[str, Any]
|
Decoded, signature-verified claims. |
required |
Returns:
| Type | Description |
|---|---|
tuple[str, ...] | None
|
tuple[str, ...] | None: The methods, in the order they were |
tuple[str, ...] | None
|
stamped. |
tuple[str, ...] | None
|
strings — a token minted before the claim existed, or by someone |
tuple[str, ...] | None
|
else. Callers treat |
tuple[str, ...] | None
|
rollout window never counts an unknown session as MFA. |
token_actor
¶
Return who is acting behind a decoded token, if anyone.
A token the admin signed to impersonate a user carries
act = {"sub": <operator id>} (RFC 8693); the user's own tokens carry
no act. A route that must not run under an impersonated session —
changing the password, moving money — refuses when this is not
None:
>>> token_actor({"sub": "u1", "act": {"sub": "op7"}})
'op7'
>>> token_actor({"sub": "u1"}) is None
True
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
payload
|
Mapping[str, Any]
|
Decoded, signature-verified claims. |
required |
Returns:
| Type | Description |
|---|---|
str | None
|
str | None: The actor's |
str | None
|
absent. A malformed |
str | None
|
comes back as |
str | None
|
delegation as the user's own session. |
ACT_CLAIM
module-attribute
¶
Claim naming the actor behind a delegated token (RFC 8693, act).
The admin's impersonation handler stamps {"sub": <operator id>} here;
read it with :func:token_actor.
TOTPHelper
¶
Stateless TOTP issuer + verifier.
Construct one per app/process. Every method is pure — the
helper holds only the issuer string shown in Authenticator
apps next to the account name. Secrets and verification codes
are passed in by the caller (typically loaded from the user
row).
Requires the [mfa] extra (pyotp).
Example:
>>> totp = TOTPHelper(issuer="My App")
>>> secret = totp.generate_secret() # base32
>>> uri = totp.provisioning_uri(secret, "ana@example.com")
>>> # render `uri` as a QR code; user scans it
>>> totp.verify(secret, "123456") # True / False
Initialize.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
issuer
|
str
|
Label rendered by the Authenticator app
alongside the account name. Use the human-readable
product name ( |
required |
generate_secret
¶
Return a fresh URL-safe base32 secret (16 chars, 80 bits).
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
Base32-encoded TOTP secret ready to feed |
str
|
meth: |
|
str
|
on the user row (encrypted at rest is preferable — |
|
str
|
consider Postgres |
Raises:
| Type | Description |
|---|---|
ImportError
|
When the |
provisioning_uri
¶
Build the otpauth:// URI for account_name.
The returned URI encodes the secret + issuer + account
name; render it as a QR code (most apps support it
directly via a <img> referencing a QR generator route on
the backend).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
secret
|
str
|
Base32 secret from :meth: |
required |
account_name
|
str
|
Identifier shown next to |
required |
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
|
Raises:
| Type | Description |
|---|---|
ImportError
|
When the |
verify
¶
Constant-time check that code matches secret now.
Says nothing about whether code was already used: a step
stays valid for the whole window, so the same 6 digits verify
again until the window moves past it. A caller that needs
single-use semantics compares :meth:matching_step against the
last accepted step — which is what
:meth:~tempest_fastapi_sdk.UserAuthService.mfa_verify does.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
secret
|
str
|
Base32 secret persisted on the user row. |
required |
code
|
str
|
6-digit code submitted by the user. |
required |
window
|
int
|
Tolerance in 30-second steps to absorb
clock drift between client and server. |
1
|
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
|
bool
|
window, |
|
bool
|
non-numeric or wrong length). |
Raises:
| Type | Description |
|---|---|
ImportError
|
When the |
matching_step
¶
Return the 30-second step code was generated from.
The step is the TOTP counter value, an integer that only moves forward — so persisting the last accepted one is what makes a code single-use: a code whose step is at or below that one has already been spent, whatever the clock says now.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
secret
|
str
|
Base32 secret persisted on the user row. |
required |
code
|
str
|
6-digit code submitted by the user. Spacing and
dashes are stripped, as in :meth: |
required |
window
|
int
|
Tolerance in 30-second steps, as in
:meth: |
1
|
Returns:
| Type | Description |
|---|---|
int | None
|
int | None: The step whose code equals |
int | None
|
when no step in the window produces it (also when |
int | None
|
non-numeric or the wrong length). Steps are scanned oldest |
int | None
|
first, the order |
int | None
|
happen to render the same 6 digits resolve to the older one. |
Raises:
| Type | Description |
|---|---|
ImportError
|
When the |
provisioning_qr_terminal
¶
provisioning_qr_terminal(
uri: str,
*,
background: ProvisioningQrBackground = "dark",
border: int = PROVISIONING_QR_BORDER,
) -> str
Draw the provisioning URI as a QR code made of terminal characters.
Each character covers one module across and two modules down, using
the half blocks ▀ (upper), ▄ (lower), █
(full) and a space, so the symbol keeps its square shape in a
terminal whose cells are about twice as tall as they are wide. A
95-character URI (issuer Tempest, ana@example.com, 32-char
secret) encodes at version 6 and prints 49 columns by 25 lines with
the default quiet zone, and a 159-character one (a 22-character
issuer, a 41-character e-mail) prints 61 columns by 31 lines — both
within 80 columns (segno 1.6.6).
The characters paint in the terminal's foreground colour, so which modules get drawn depends on the background: on a dark terminal the light modules (and the quiet zone) are drawn, which is what makes the symbol read dark-on-light to the camera; on a light terminal the dark modules are drawn.
Example:
>>> from tempest_fastapi_sdk import TOTPHelper, provisioning_qr_terminal
>>> totp = TOTPHelper(issuer="Tempest")
>>> uri = totp.provisioning_uri(totp.generate_secret(), "ana@example.com")
>>> print(provisioning_qr_terminal(uri)) # doctest: +SKIP
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
uri
|
str
|
The |
required |
background
|
ProvisioningQrBackground
|
|
'dark'
|
border
|
int
|
Quiet zone in modules. See
:data: |
PROVISIONING_QR_BORDER
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The lines of the drawing joined by |
str
|
trailing newline — ready for |
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
ImportError
|
When |
provisioning_qr_data_uri
¶
provisioning_qr_data_uri(
uri: str,
*,
kind: ProvisioningQrKind = "svg",
scale: int = PROVISIONING_QR_SCALE,
border: int = PROVISIONING_QR_BORDER,
) -> str
Encode the provisioning URI as a QR code image in a data: URI.
Goes straight into <img src="..."> or a mobile image view, so
the app shows the QR code without a QR library of its own. With
segno 1.6.6 and the defaults, the SVG data: URI for a
95-character URI measured 3 642 to 4 062 characters across 500
random secrets — the path length follows the module pattern.
Example:
>>> from tempest_fastapi_sdk import TOTPHelper, provisioning_qr_data_uri
>>> totp = TOTPHelper(issuer="Tempest")
>>> uri = totp.provisioning_uri(totp.generate_secret(), "ana@example.com")
>>> provisioning_qr_data_uri(uri).startswith("data:image/svg+xml;base64,")
True
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
uri
|
str
|
The |
required |
kind
|
ProvisioningQrKind
|
|
'svg'
|
scale
|
int
|
Pixels (SVG user units) per module. See
:data: |
PROVISIONING_QR_SCALE
|
border
|
int
|
Quiet zone in modules. See
:data: |
PROVISIONING_QR_BORDER
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
|
str
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
ImportError
|
When |
ProvisioningQrKind
module-attribute
¶
Image format of :func:provisioning_qr_data_uri.
ProvisioningQrBackground
module-attribute
¶
Background colour of the terminal :func:provisioning_qr_terminal prints to.
PROVISIONING_QR_ERROR
module-attribute
¶
Error-correction level of the provisioning QR code: M (15 %).
The symbol is scanned off a screen, not off a creased voucher, so the
recovery that :data:tempest_fastapi_sdk.pdf.QR_ERROR_CORRECTION buys
with H is spent on modules the camera does not need. segno still
raises the level when the chosen version has room for it
(boost_error), so the symbol is never denser than M requires.
PROVISIONING_QR_BORDER
module-attribute
¶
Quiet zone, in modules, around the provisioning QR code.
The four modules ISO/IEC 18004 asks for. Unlike the voucher, nothing
around the symbol supplies white space: a terminal is usually dark and a
data: URI lands wherever the app puts it, so the quiet zone has to
be part of the drawing.
PROVISIONING_QR_SCALE
module-attribute
¶
Pixels (SVG user units) per module in :func:provisioning_qr_data_uri.
A 95-character otpauth:// URI encodes at version 6 (41 modules), so
the default image is (41 + 2 * 4) * 5 = 245 pixels wide — readable
in an <img> with no CSS. The SVG scales without loss either way.
EmailUtils
¶
EmailUtils(
host: str,
port: int,
*,
from_addr: str,
username: str | None = None,
password: str | None = None,
use_tls: bool = False,
use_starttls: bool = True,
timeout: float = 30.0,
template_dir: str | Path | None = None,
enabled: bool = True,
)
Send transactional emails via SMTP.
Connection configuration is supplied at construction time; each
:meth:send call opens a fresh SMTP connection (aiosmtplib's
high-level send helper handles connect/login/quit). For
high-volume scenarios consider holding a persistent connection
via aiosmtplib.SMTP directly.
Attributes:
| Name | Type | Description |
|---|---|---|
host |
str
|
SMTP server hostname. |
port |
int
|
SMTP port. |
from_addr |
str
|
Default sender address used as the |
use_tls |
bool
|
Whether to connect using SSL/TLS from the start (port 465 style). |
use_starttls |
bool
|
Whether to upgrade to TLS via STARTTLS after connect (port 587 style). Opportunistic — the upgrade happens only when the server advertises STARTTLS, so a plain server (e.g. MailHog) is left as-is instead of raising. |
enabled |
bool
|
|
Initialize.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
host
|
str
|
SMTP server hostname. |
required |
port
|
int
|
SMTP port. Common values: |
required |
from_addr
|
str
|
Default sender address. |
required |
username
|
str | None
|
Auth username. |
None
|
password
|
str | None
|
Auth password. |
None
|
use_tls
|
bool
|
Connect using SSL/TLS immediately. Set
this for port |
False
|
use_starttls
|
bool
|
Upgrade to TLS via STARTTLS after
connect. Set this for port |
True
|
timeout
|
float
|
SMTP socket timeout in seconds. |
30.0
|
template_dir
|
str | Path | None
|
Directory holding Jinja2
templates for :meth: |
None
|
enabled
|
bool
|
|
True
|
Raises:
| Type | Description |
|---|---|
ImportError
|
When the |
Notes
Jinja environments are memoized one per resolved locale, plus a
None key for locale-less renders, and built lazily on first
use.
require_enabled
¶
Refuse to go on when the e-mail integration is switched off.
Called first by :meth:send and :meth:send_many. Code that has
to decide before a side effect whether a mail can go out — the
auth service refuses a signup that would need an activation link —
calls it directly.
Raises:
| Type | Description |
|---|---|
IntegrationDisabledException
|
When the mailer was built with
|
send
async
¶
send(
to: str | Iterable[str],
subject: str,
body: str,
*,
html: str | None = None,
cc: Iterable[str] | None = None,
bcc: Iterable[str] | None = None,
attachments: Iterable[Path | EmailAttachment] | None = None,
reply_to: str | None = None,
from_addr: str | None = None,
) -> None
Send a single email.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
to
|
str | Iterable[str]
|
Recipient address(es). Listed
in the |
required |
subject
|
str
|
Subject line. |
required |
body
|
str
|
Plain-text body. Always sent; the HTML
alternative is added as a multipart child when
|
required |
html
|
str | None
|
Optional HTML alternative body. |
None
|
cc
|
Iterable[str] | None
|
Additional |
None
|
bcc
|
Iterable[str] | None
|
|
None
|
attachments
|
Iterable[Path | EmailAttachment] | None
|
Files to
attach. A |
None
|
reply_to
|
str | None
|
Value for the |
None
|
from_addr
|
str | None
|
Override the default sender for this message. |
None
|
Raises:
| Type | Description |
|---|---|
IntegrationDisabledException
|
When the mailer was built with
|
EmailDeliveryException
|
When the transport fails — the host
does not resolve, the connection is refused or times out,
the TLS handshake fails, the login is rejected, or the
server refuses the message ( |
OSError
|
When an |
ValueError
|
When an |
Notes
STARTTLS is negotiated opportunistically: aiosmtplib upgrades
the connection only when the server advertises support, so a
plain server such as MailHog no longer hard-fails with
SMTP STARTTLS extension not supported by server. Passing
start_tls=True would force the upgrade and raise there
instead. use_tls (implicit TLS / SMTPS) is mutually exclusive
with STARTTLS, so the upgrade is disabled in that case.
send_many
async
¶
send_many(
recipients: Iterable[str],
subject: str,
body: str,
*,
html: str | None = None,
reply_to: str | None = None,
from_addr: str | None = None,
batch_size: int = DEFAULT_BULK_BATCH_SIZE,
max_concurrency: int = DEFAULT_BULK_CONCURRENCY,
) -> BulkEmailReport
Send one message to many recipients and report what happened.
The loop a caller would otherwise write — for user in users:
await mailer.send(...) — has four problems this method exists to
remove, and the first two are why it is not simply gather over
:meth:send:
- One connection per message. :meth:
sendopens, authenticates and quits every time, so five thousand recipients cost five thousand TLS handshakes. Here each batch opens one connection and reuses it, which is where the time goes: connections drop fromlen(recipients)tolen(recipients) / batch_size. - Unbounded fan-out.
gatherover the whole list opens as many connections as there are recipients, and every hosted SMTP provider caps how many a sender may hold at once — past the cap the extra ones are throttled or dropped, and the cap belongs to the provider, not to us. At mostmax_concurrencyconnections are open at once — the same default the Web Push broadcast uses. - Partial failure is unreportable. The first bad address ends
the loop; wrapping each item in
try/exceptthrows the detail away. Per-recipient failures never raise here, they land in the report. - A dead address looks like a busy one. SMTP separates
5xx(this mailbox does not exist — stop trying) from4xx(full, greylisted — try later), and the two call for opposite actions: prune versus requeue. They are reported apart.
Concurrency is per connection, not per message: SMTP is a serial protocol on a single socket, so a batch is sent sequentially over its own connection and parallelism comes from running several batches at once.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
recipients
|
Iterable[str]
|
Addresses to deliver to. Each gets its own message — nobody sees anyone else's address. |
required |
subject
|
str
|
Subject line, shared by every message. |
required |
body
|
str
|
Plain-text body, shared by every message. |
required |
html
|
str | None
|
Optional HTML alternative body. |
None
|
reply_to
|
str | None
|
Value for the |
None
|
from_addr
|
str | None
|
Override the default sender. |
None
|
batch_size
|
int
|
Recipients per connection. Larger means fewer handshakes and a longer-lived connection, which some providers cut off on their own schedule. |
DEFAULT_BULK_BATCH_SIZE
|
max_concurrency
|
int
|
Connections open at once. |
DEFAULT_BULK_CONCURRENCY
|
Returns:
| Name | Type | Description |
|---|---|---|
BulkEmailReport |
BulkEmailReport
|
Delivered count plus the permanent and |
BulkEmailReport
|
transient failures, each with the code and message the server |
|
BulkEmailReport
|
gave. |
Raises:
| Type | Description |
|---|---|
IntegrationDisabledException
|
When the mailer was built with
|
EmailDeliveryException
|
Only for a failure of the operation
itself — the host does not resolve, the connection is
refused or times out, the TLS handshake fails,
authentication is rejected, the server drops the
connection mid-batch. Same |
ValueError
|
When |
render_template
¶
Render a Jinja2 template from template_dir with context.
The Jinja environment is built lazily on first call and
memoized per locale — subsequent renders for the same locale
reuse the same loader. HTML autoescaping is enabled for
.html / .htm / .xml templates so caller-supplied
values cannot break out into markup.
Template lookup order (first hit wins):
template_dir/<locale>/<name>— project override, this locale.template_dir/<name>— project override, legacy flat layout.<sdk>/auth/templates/<locale>/<name>— SDK bundled, this locale (e.g. the localized activation / password-reset emails).
When locale is None the locale subdirectories are skipped
and only the flat template_dir and the SDK bundled root are
searched — this preserves the pre-0.59 behavior for generic
callers that ship their own template_dir.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
template_name
|
str
|
Template filename (e.g. |
required |
context
|
dict[str, Any]
|
Variables exposed inside the template. |
required |
locale
|
str | None
|
Canonical locale (e.g. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
Rendered template body — pass this directly to |
str
|
meth: |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
When |
ImportError
|
When Jinja2 is missing (it ships with the
|
TemplateNotFound
|
When the file cannot be located
under |
Example:
>>> emails = EmailUtils(..., template_dir="emails/")
>>> html = emails.render_template(
... "welcome.html",
... {"user_name": "Ana", "app_url": "https://app/"},
... locale="pt-BR",
... )
>>> await emails.send(
... "ana@example.com",
... subject="Bem-vinda!",
... body="Bem-vinda, Ana!",
... html=html,
... )
Notes
Templates resolve through a ChoiceLoader: the project's own
template_dir first, then the SDK's bundled ones
(auth/activation, auth/password_reset). That is what lets
the bundled auth flow render its default emails without the
caller having to ship a template_dir at all.
The bundled templates live under per-locale subdirectories
(pt-BR / en-US), so a locale-less render falls back to
the default locale's subdirectory to reach them.
EmailAttachment
dataclass
¶
A file attached from memory, without touching the disk.
Pass it in attachments next to (or instead of) a :class:~pathlib.Path
— for example the bytes a PDF renderer returns.
Attributes:
| Name | Type | Description |
|---|---|---|
filename |
str
|
Name the recipient sees. Must be non-empty and free
of line breaks, NUL, |
content |
bytes
|
The file's bytes. |
content_type |
str | None
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
resolved_content_type
property
¶
The content type the message is sent with.
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
|
str
|
from |
from_path
classmethod
¶
from_path(path: Path) -> EmailAttachment
Read a file from disk into an attachment.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
Path
|
The file to read. Its |
required |
Returns:
| Name | Type | Description |
|---|---|---|
EmailAttachment |
EmailAttachment
|
The attachment, with |
EmailAttachment
|
|
Raises:
| Type | Description |
|---|---|
OSError
|
When the file cannot be read. |
ValueError
|
When the file name carries a forbidden character. |
UploadUtils
¶
UploadUtils(
source: str | Path | AsyncMinIOClient | None = None,
*,
backend: UploadStorage | None = None,
max_size_bytes: int | None = None,
allowed_extensions: set[str] | None = None,
allowed_mimetypes: set[str] | None = None,
verify_magic_bytes: bool = False,
require_known_signature: bool = True,
chunk_size: int = 1024 * 1024,
)
Persist uploaded files to local disk with opt-in validation.
Validation is incremental: extension and MIME type are checked
against the configured whitelists before reading any bytes; the
file's real content is optionally sniffed from its first bytes
(verify_magic_bytes); and size is enforced as the stream is
consumed so oversized uploads don't fill the disk before being
rejected.
Saved files are streamed in chunks so memory usage stays bounded regardless of the upload size.
Attributes:
| Name | Type | Description |
|---|---|---|
upload_dir |
Path | None
|
Local base directory when constructed
with a path; |
max_size_bytes |
int | None
|
Reject uploads larger than this.
|
allowed_extensions |
set[str] | None
|
Whitelist of file
extensions (lowercase, no dot). |
allowed_mimetypes |
set[str] | None
|
Whitelist of MIME types
(lowercase). |
require_known_signature |
bool
|
With |
verify_magic_bytes |
bool
|
When |
Initialize with a local directory, a MinIO client, or a backend.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
str | Path | AsyncMinIOClient | None
|
Where uploads
are persisted. A directory path stores files on local disk
(created if missing); an |
None
|
backend
|
UploadStorage | None
|
A pre-built storage backend to
use directly, bypassing the |
None
|
max_size_bytes
|
int | None
|
Reject uploads larger than
this. |
None
|
allowed_extensions
|
set[str] | None
|
Whitelist of file
extensions. Leading dots and case are normalized
internally so |
None
|
allowed_mimetypes
|
set[str] | None
|
Whitelist of MIME
types (case-insensitive, e.g. |
None
|
verify_magic_bytes
|
bool
|
Sniff the first bytes of each
upload and reject content that does not match its
declared type / the allow-list. See the class
attribute docs for the caveat. Default |
False
|
require_known_signature
|
bool
|
Whether an upload whose
signature :func: |
True
|
chunk_size
|
int
|
Stream read chunk in bytes. Defaults to 1 MiB; raise to trade memory for fewer syscalls. |
1024 * 1024
|
Raises:
| Type | Description |
|---|---|
ValueError
|
When neither |
ImportError
|
When the local backend is selected but the
|
validate
¶
Validate extension and MIME type before reading the stream.
Size and content (magic bytes) cannot be checked here because
they require reading the stream; they are enforced incrementally
in :meth:save as bytes are consumed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file
|
UploadFile
|
The FastAPI upload to validate. |
required |
Raises:
| Type | Description |
|---|---|
InvalidFileTypeException
|
If the extension or MIME type is not in the configured whitelist. |
save
async
¶
save(
file: UploadFile,
*,
subdir: str = "",
filename: str | None = None,
keep_original_name: bool = False,
content_validator: Callable[[bytes], bool] | None = None,
hasher: Any | None = None,
) -> Path
Validate and persist file to the configured backend.
The backend (local disk or MinIO) is the one chosen at
construction — the validation pipeline (extension / MIME / size /
magic bytes / content_validator) is identical for either.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file
|
UploadFile
|
The FastAPI upload. |
required |
subdir
|
str
|
Optional sub-directory / key prefix
(e.g. |
''
|
filename
|
str | None
|
Explicit final filename (e.g.
|
None
|
keep_original_name
|
bool
|
When |
False
|
content_validator
|
Callable[[bytes], bool] | None
|
Optional
predicate run on the first chunk read from the stream.
Returning It sees only that first chunk, which is what makes
rejecting early cheap — and what makes it useless for
anything that must read the whole file. Accumulating a
SHA-256 inside it digests the first chunk and nothing
else, and the result looks like a valid digest of the
upload. Pass |
None
|
hasher
|
Any | None
|
A |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
Path |
Path
|
|
Path
|
( |
|
Path
|
for the bare key. |
Raises:
| Type | Description |
|---|---|
InvalidFileTypeException
|
If the extension/MIME violates the
whitelist, the |
FileTooLargeException
|
If the stream exceeds
|
delete
async
¶
Delete a previously saved object via the configured backend.
For the local backend the key resolves under the base directory
(path-traversal attempts raise InvalidFileTypeException); for
MinIO it is the object key.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
Path | str
|
The storage key returned by :meth: |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
|
bool
|
|
Raises:
| Type | Description |
|---|---|
InvalidFileTypeException
|
Local backend, when |
replace
async
¶
replace(
old_key: Path | str | None,
file: UploadFile,
*,
subdir: str = "",
filename: str | None = None,
keep_original_name: bool = False,
content_validator: Callable[[bytes], bool] | None = None,
hasher: Any | None = None,
) -> Path
Save a new object and delete the one it replaces.
The common "swap the user's avatar / attachment" flow in one call:
the new file is persisted first (so a validation error or a
write failure leaves the old object untouched), then old_key
is deleted through the same configured backend — avoiding the
mistake of saving through one backend and deleting through another.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
old_key
|
Path | str | None
|
Storage key of the object being
replaced (typically the value currently stored on the
model). |
required |
file
|
UploadFile
|
The new FastAPI upload. |
required |
subdir
|
str
|
Optional sub-directory / key prefix. |
''
|
filename
|
str | None
|
Explicit final filename. Same rules as
:meth: |
None
|
keep_original_name
|
bool
|
Preserve the upload's original
filename when |
False
|
content_validator
|
Callable[[bytes], bool] | None
|
Optional
predicate run on the first chunk; see :meth: |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
Path |
Path
|
|
Raises:
| Type | Description |
|---|---|
InvalidFileTypeException
|
If validation rejects the new file (the old object is left intact). |
FileTooLargeException
|
If the new stream exceeds
|
SNIFFABLE_MIMETYPES
module-attribute
¶
SNIFFABLE_MIMETYPES: frozenset[str] = frozenset(
{mime for _signature, mime in _MAGIC_SIGNATURES} | {"image/webp", "image/heic"}
)
The MIME types :func:sniff_mime can recognize from the bytes.
A type outside this set carries no signature to check — plain text, CSV,
JSON, most office and archive formats — so "no signature found" says
nothing about it. Membership is what lets
require_known_signature=False tell a contradiction (declared
image/jpeg, no JPEG signature) apart from an unverifiable upload
(declared text/csv, and text has no magic bytes).
sniff_mime
¶
Detect a file's MIME type from its leading bytes.
Performs magic-byte sniffing on the first bytes read from an upload
stream and returns the MIME the bytes actually represent — regardless
of the Content-Type the client declared. Compare the result with
the declared type (or an allow-list) to reject content/declaration
mismatches such as an HTML payload uploaded as image/jpeg.
Recognizes JPEG, PNG, GIF, BMP, WebP, HEIC and PDF. Returns None
for anything else (text, archives, office documents, audio/video
containers, AVIF, …) — absence of a match means "not one of the
sniffable binary formats", not "invalid".
HEIC is an ISO-BMFF ftyp box: prefix[4:8] is ftyp and
prefix[8:12] the major brand. A major brand in
:data:HEIC_BRANDS is HEIC; a codec-neutral one
(:data:HEIF_STRUCTURAL_BRANDS) is HEIC only when a compatible brand
of the box (from byte 16 up to the box size) is in
:data:HEIC_BRANDS. An AVIF file (major brand avif, or mif1
with only AV1 compatible brands) returns None.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prefix
|
bytes
|
The first bytes of the file (≥32 bytes
recommended so the WebP |
required |
Returns:
| Type | Description |
|---|---|
str | None
|
str | None: The detected MIME type, or |
HEIC_BRANDS
module-attribute
¶
HEIC_BRANDS: frozenset[bytes] = frozenset(
{b"heic", b"heix", b"heim", b"heis", b"hevc", b"hevx", b"hevm", b"hevs"}
)
ISO-BMFF ftyp brands of an HEVC-coded HEIF file (HEIC).
Ported from libheif's heif_get_file_mime_type
(libheif/api/libheif/heif_brands.cc, commit 1b2a9a8), which maps
heic/heix/heim/heis to image/heic and
hevc/hevx/hevm/hevs to image/heic-sequence: the
HEVC-coded brands of HEIF (ISO/IEC 23008-12). :func:sniff_mime folds
both groups into image/heic, so an image sequence
declared as image/heic is not refused as a contradiction.
AV1 brands (avif, avis) are deliberately absent: an AVIF file is
a HEIF container too, but not HEIC.
HEIF_STRUCTURAL_BRANDS
module-attribute
¶
Codec-neutral HEIF brands (image item, image sequence).
Ported from libheif's heif_get_file_mime_type
(libheif/api/libheif/heif_brands.cc, commit 1b2a9a8), which reports
them as the generic image/heif/image/heif-sequence. Some encoders
write one of them as the major brand of an HEIC file, and others of an
AVIF file, so on their own they do not say which codec is inside:
:func:sniff_mime reports image/heic for them only when a compatible
brand of the ftyp box is in :data:HEIC_BRANDS.
read_upload_capped
async
¶
Read an uploaded file into memory, refusing one that is too large.
Reads in :data:UPLOAD_READ_CHUNK_BYTES chunks and stops at the
ceiling instead of calling await upload.read() and measuring
afterwards: measuring afterwards means the oversized upload already
occupied the memory it was meant to be denied. This is the reader
every route of the SDK that takes a whole file into memory uses
(make_genai_router's /transcribe, make_voice_router, and
make_vision_router).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
upload
|
UploadFile
|
The uploaded file. |
required |
max_bytes
|
int
|
The largest accepted size, in bytes. |
required |
label
|
str
|
What the file is, used in the error message
( |
'upload'
|
Returns:
| Name | Type | Description |
|---|---|---|
bytes |
bytes
|
The whole upload. |
Raises:
| Type | Description |
|---|---|
UploadTooLargeException
|
When the upload exceeds |
UPLOAD_READ_CHUNK_BYTES
module-attribute
¶
Chunk size :func:read_upload_capped reads with (1 MiB).
The ceiling is checked after every chunk, so an oversized upload costs at
most max_bytes plus one chunk of memory before it is refused.
relative_luminance
¶
Return the WCAG relative luminance of a hex color.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
color
|
str
|
|
required |
Returns:
| Type | Description |
|---|---|
float | None
|
float | None: |
float | None
|
|
is_light
¶
Tell whether a background needs dark text.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
color
|
str
|
The background. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
|
bool
|
data: |
|
bool
|
assumed dark, the case a named brand color usually is. |
DownloadUtils
¶
DownloadUtils(source: str | Path | AsyncMinIOClient)
Serve files for download — from a local directory or MinIO.
Pick the backend once at construction:
- pass a directory (
DownloadUtils("var/uploads")) to serve files from local disk, or - pass an :class:
~tempest_fastapi_sdk.AsyncMinIOClient(DownloadUtils(minio_client)) to stream objects straight from a bucket.
Then call :meth:download with the file's path/key for either backend.
For local disk, all reads are confined to base_dir: a path that
resolves outside it (../ traversal, absolute paths, symlink
escapes) raises :class:NotFoundException rather than leaking
arbitrary files — the same 404 as a missing file.
Attributes:
| Name | Type | Description |
|---|---|---|
base_dir |
Path | None
|
Resolved local root, or |
Initialize with a local directory or a MinIO client.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
str | Path | AsyncMinIOClient
|
A directory path to
serve files from local disk, or an |
required |
download
async
¶
download(
key: str,
*,
subdir: str = "",
filename: str | None = None,
media_type: str | None = None,
as_attachment: bool = True,
request: Request | None = None,
cache_control: str | None = None,
headers: dict[str, str] | None = None,
) -> Response
Build a download response for key from the configured backend.
Works the same for both backends: local disk returns a streamed
FileResponse (range-aware), MinIO returns a StreamingResponse
proxied from the bucket — range- and validator-aware when
request is passed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
File path (local, relative to |
required |
subdir
|
str
|
Optional sub-directory / key prefix. |
''
|
filename
|
str | None
|
Name presented to the client. Defaults to
the basename of |
None
|
media_type
|
str | None
|
MIME type. Guessed/derived when omitted. |
None
|
as_attachment
|
bool
|
|
True
|
request
|
Request | None
|
The incoming request. MinIO mode needs
it to answer |
None
|
cache_control
|
str | None
|
|
None
|
headers
|
dict[str, str] | None
|
Extra response headers. One
named like a security default ( |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
Response |
Response
|
A |
Response
|
(MinIO) ready to return from a router. |
Raises:
| Type | Description |
|---|---|
NotFoundException
|
Local mode, when the path escapes |
S3Error
|
MinIO mode, when the object is missing. |
resolve
¶
Resolve a client-supplied path safely under base_dir.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
relative_path
|
Path | str
|
Path relative to |
required |
subdir
|
str
|
Optional sub-directory between |
''
|
Returns:
| Name | Type | Description |
|---|---|---|
Path |
Path
|
The resolved, existing file path. |
Raises:
| Type | Description |
|---|---|
NotFoundException
|
If the path escapes |
RuntimeError
|
When this |
file_response
¶
file_response(
relative_path: Path | str,
*,
subdir: str = "",
filename: str | None = None,
media_type: str | None = None,
as_attachment: bool = True,
headers: dict[str, str] | None = None,
) -> FileResponse
Build a FileResponse streaming a file from disk.
The response is streamed in chunks by Starlette and supports HTTP range requests, so large files never load fully into memory.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
relative_path
|
Path | str
|
Path to the file, relative to
|
required |
subdir
|
str
|
Optional sub-directory under |
''
|
filename
|
str | None
|
Name presented to the client. Defaults to the file's own basename. |
None
|
media_type
|
str | None
|
MIME type. Guessed from the filename
extension when omitted, falling back to
|
None
|
as_attachment
|
bool
|
|
True
|
headers
|
dict[str, str] | None
|
Extra response headers. One
named like a security default ( |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
FileResponse |
FileResponse
|
The response to return from a router. |
Raises:
| Type | Description |
|---|---|
NotFoundException
|
If the file cannot be located (see
:meth: |
stream
¶
stream(
content: bytes | Iterable[bytes] | AsyncIterable[bytes],
*,
filename: str,
media_type: str | None = None,
as_attachment: bool = True,
headers: dict[str, str] | None = None,
) -> StreamingResponse
Build a StreamingResponse from in-memory bytes or a generator.
Use when the payload is produced on the fly (a generated report, a
zip built in memory, decrypted bytes) rather than read from
base_dir. base_dir is not consulted here.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
content
|
bytes | Iterable[bytes] | AsyncIterable[bytes]
|
The
payload. Raw |
required |
filename
|
str
|
Name presented to the client. |
required |
media_type
|
str | None
|
MIME type. Guessed from |
None
|
as_attachment
|
bool
|
|
True
|
headers
|
dict[str, str] | None
|
Extra response headers. One
named like a security default ( |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
StreamingResponse |
StreamingResponse
|
The response to return from a router. |
INLINE_SAFE_MEDIA_TYPES
module-attribute
¶
INLINE_SAFE_MEDIA_TYPES: frozenset[str] = frozenset(
{
"application/pdf",
"audio/aac",
"audio/flac",
"audio/mp4",
"audio/mpeg",
"audio/ogg",
"audio/wav",
"audio/webm",
"audio/x-wav",
"image/avif",
"image/gif",
"image/jpeg",
"image/png",
"image/webp",
"text/plain",
"video/mp4",
"video/ogg",
"video/quicktime",
"video/webm",
}
)
Media types a download may serve inline when the caller asks for it.
A download answers on the API's own origin, and inline is what lets the
browser render the bytes as a document of that origin. text/html there
is a page that runs script with the viewer's session on the API;
image/svg+xml is the same risk behind an image type, since SVG can carry
<script>. The list is therefore an
allowlist: a type absent from it is served as attachment even with
as_attachment=False, and so is a type the SDK does not know at build time
(None).
What is inside is raster images, application/pdf, text/plain and
common audio and video — the inline uses a download helper is asked for
(<img>, <video>, viewing a PDF or a log in the browser). SVG and HTML
are left out on purpose. To serve another type inline, build the response
yourself; the helpers do not take an override, because the whole point is
that an uploader-chosen type cannot reach inline.
guess_media_type
¶
Guess a file's media type from its name, independent of the host.
Looks the extension up in this module's table first, then asks
:func:mimetypes.guess_type. The table is what keeps the answer the
same on a developer machine and in a slim container image that has no
/etc/mime.types.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filename
|
str
|
A file name or path; only the extension is read, case-insensitively. |
required |
Returns:
| Type | Description |
|---|---|
str | None
|
str | None: The media type, or |
str | None
|
the extension. |
ImageMediaTypeEnum
¶
Bases: BaseStrEnum
Image media types whose bytes :func:sniff_mime can verify.
Exactly the image/* members of
:data:~tempest_fastapi_sdk.utils.upload.SNIFFABLE_MIMETYPES, so
every member can be checked against the upload's real content with
:meth:matches. Use it as the type of a Pydantic field that carries a
declared Content-Type: the input is matched case-insensitively,
with surrounding whitespace stripped, and the aliases the upload
helpers accept (image/jpg, image/pjpeg → JPEG, image/x-png
→ PNG) resolve to the canonical member. Anything else fails
validation with Pydantic's usual enum error (422 in a route),
and the JSON Schema lists the canonical values.
Examples:
>>> ImageMediaTypeEnum(" Image/JPG ")
<ImageMediaTypeEnum.JPEG: 'image/jpeg'>
>>> ImageMediaTypeEnum.HEIC.extension
'heic'
extension
property
¶
The conventional file extension, lowercase and without the dot.
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
|
str
|
|
matches
¶
Tell whether data carries this type's signature.
The declared type is client-controlled; this checks it against
what the bytes actually are, via :func:sniff_mime.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
bytes
|
The file content, or at least its first 32
bytes (enough for every signature, including the
compatible brands of an HEIF |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
|
bool
|
type in |
image_media_type_field
¶
image_media_type_field(
*allowed: ImageMediaTypeEnum,
title: str = "Image type",
description: str | None = None,
examples: list[str] | None = None,
) -> FieldInfo
Build the metadata of a field accepting some ImageMediaTypeEnum values.
For a schema that takes the declared type of an upload — the photo of
an evidence, of a product — and must refuse the types it does not
store. Put it in Annotated next to ImageMediaTypeEnum, so the static
type is the enum::
class EvidenceCreateSchema(BaseSchema):
photo_type: Annotated[
ImageMediaTypeEnum,
image_media_type_field(
ImageMediaTypeEnum.JPEG,
ImageMediaTypeEnum.PNG,
ImageMediaTypeEnum.WEBP,
ImageMediaTypeEnum.HEIC,
title="Photo type",
),
]
The value is normalized by :class:ImageMediaTypeEnum ("IMAGE/JPG "
becomes image/jpeg), a type outside allowed is a 422, and
the OpenAPI schema lists allowed only.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*allowed
|
ImageMediaTypeEnum
|
The accepted types. None means every
member of :class: |
()
|
title
|
str
|
The field title. |
'Image type'
|
description
|
str | None
|
The field description. |
None
|
examples
|
list[str] | None
|
The field examples. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
FieldInfo |
FieldInfo
|
The field metadata, carrying the restriction. |
AllowedImageMediaTypes
¶
AllowedImageMediaTypes(allowed: Sequence[ImageMediaTypeEnum])
Pydantic metadata restricting an ImageMediaTypeEnum field to a subset.
Validates after the enum itself, so the normalization the enum already
does — case, surrounding whitespace, aliases such as image/jpg — runs
first, and narrows the OpenAPI schema to the allowed values only.
Attributes:
| Name | Type | Description |
|---|---|---|
allowed |
tuple[ImageMediaTypeEnum, ...]
|
The accepted types, in the order the schema lists them. |
Store the accepted types.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
allowed
|
Sequence[ImageMediaTypeEnum]
|
The accepted types. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
RawTextField
module-attribute
¶
String kept exactly as sent, leading and trailing whitespace included.
:class:~tempest_fastapi_sdk.BaseSchema sets str_strip_whitespace=True,
which is right for names and e-mails and wrong for content: a streaming
delta " mundo" became "mundo" and a prompt reached the model
different from what the client sent (#718). Annotating the field with this
type overrides the model-wide setting for that field only, on construction
and on assignment (validate_assignment). Measured on pydantic 2.13.5.
XLSX_MEDIA_TYPE
module-attribute
¶
Media type of an Office Open XML workbook (.xlsx).
Ported from the media-types 10.1.0 package's /etc/mime.types.
DOCX_MEDIA_TYPE
module-attribute
¶
DOCX_MEDIA_TYPE: str = (
"application/vnd.openxmlformats-officedocument.wordprocessingml.document"
)
Media type of an Office Open XML document (.docx).
Ported from the media-types 10.1.0 package's /etc/mime.types.
PPTX_MEDIA_TYPE
module-attribute
¶
PPTX_MEDIA_TYPE: str = (
"application/vnd.openxmlformats-officedocument.presentationml.presentation"
)
Media type of an Office Open XML presentation (.pptx).
Ported from the media-types 10.1.0 package's /etc/mime.types.
strip_image_metadata
¶
strip_image_metadata(
data: bytes,
media_type: ImageMediaTypeEnum | str,
*,
max_pixels: int = DEFAULT_MAX_IMAGE_PIXELS,
jpeg_quality: int = DEFAULT_JPEG_QUALITY,
webp_quality: int = DEFAULT_WEBP_QUALITY,
) -> bytes
Re-encode an image in its own format, without any metadata.
The image is decoded by Pillow, turned upright according to its EXIF
orientation (ImageOps.exif_transpose, so a portrait photo does not
come back lying on its side once the orientation tag is gone), and
encoded again from its pixels alone. EXIF (GPS, device, capture time,
embedded thumbnail), XMP, IPTC, the ICC color profile, comments and
PNG text chunks are all left behind. The pixel size is kept (with
width and height swapped when the orientation rotates by 90 degrees),
and so are the mode and the transparency.
Format notes:
- JPEG is re-encoded at
jpeg_quality, which is lossy: the bytes differ from the source even for an image with no metadata. - WEBP stays lossless when the source is lossless; a lossy source
is re-encoded at
webp_quality. - GIF and WEBP animations come back as their first frame. Re-encoding every frame would multiply the decode cost by a frame count the client controls; a service that must keep animations should not route them through this function.
- Dropping the ICC profile means the pixels are read as sRGB. Nothing changes for an sRGB photo; a wide-gamut one (Display P3, common on recent phones) can shift slightly in saturation.
image/heicis refused: Pillow ships no HEIC codec.
The function is CPU-bound and synchronous; from an async route, call
it through asyncio.to_thread.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
bytes
|
The image file content. |
required |
media_type
|
ImageMediaTypeEnum | str
|
The declared media type,
usually the client's |
required |
max_pixels
|
int
|
Ceiling on |
DEFAULT_MAX_IMAGE_PIXELS
|
jpeg_quality
|
int
|
JPEG quality, |
DEFAULT_JPEG_QUALITY
|
webp_quality
|
int
|
Lossy WEBP quality, |
DEFAULT_WEBP_QUALITY
|
Returns:
| Name | Type | Description |
|---|---|---|
bytes |
bytes
|
The re-encoded image, in the declared format. |
Raises:
| Type | Description |
|---|---|
ImportError
|
When the |
ValueError
|
When |
ImageFormatUnsupportedException
|
When |
ImageDecodeException
|
When the bytes are not an image of an
accepted format, or are truncated or corrupt ( |
ImageTypeMismatchException
|
When the bytes are a different
accepted format than the declared one ( |
ImageTooLargeException
|
When the image has more than
|
Examples:
DEFAULT_MAX_IMAGE_PIXELS
module-attribute
¶
Default ceiling on width * height accepted by :func:strip_image_metadata.
Fits the full-resolution output of a 48 or 50 megapixel phone sensor (8064 x 6048 is 48.8 million pixels). Memory grows with the pixel count: measured on Pillow 13.0.0 with an 8000 x 6000 JPEG (48 million pixels), the call's peak memory rose by about 186 MB for an upright photo and 368 MB for one its orientation rotates by 90 degrees (Pillow holds RGB at four bytes per pixel, and the rotation keeps two copies for a moment). Raise the ceiling only with that cost in mind.
DEFAULT_JPEG_QUALITY
module-attribute
¶
Default JPEG quality used when re-encoding (Pillow's own default is 75).
DEFAULT_WEBP_QUALITY
module-attribute
¶
Default quality for a lossy WEBP re-encode (Pillow's own default is 80).
A lossless source is re-encoded lossless, where quality does not apply.
FileStoreUtils
¶
FileStoreUtils(
source: str | Path | AsyncMinIOClient,
*,
max_size_bytes: int | None = None,
allowed_extensions: set[str] | None = None,
allowed_mimetypes: set[str] | None = None,
verify_magic_bytes: bool = False,
chunk_size: int = 1024 * 1024,
)
Single entry point for storing, serving and signing files.
Composes an :class:~tempest_fastapi_sdk.utils.upload.UploadUtils and a
:class:~tempest_fastapi_sdk.utils.download.DownloadUtils over one
storage backend, plus presign shortcuts for the MinIO backend. Use it
when a service both persists and serves the same files and you want one
configured object instead of three.
The individual pieces stay reachable for escape hatches:
:attr:uploader, :attr:downloader, :attr:backend and
:attr:client.
Attributes:
| Name | Type | Description |
|---|---|---|
uploader |
UploadUtils
|
Validation + persistence half. |
downloader |
DownloadUtils
|
Read + serve half. |
backend |
UploadStorage
|
The shared storage backend
( |
client |
AsyncMinIOClient | None
|
The MinIO client when
MinIO-backed, otherwise |
Build the facade, selecting the backend from source.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
str | Path | AsyncMinIOClient
|
A directory path for
local disk, or an |
required |
max_size_bytes
|
int | None
|
Reject uploads larger than this.
|
None
|
allowed_extensions
|
set[str] | None
|
Whitelist of file extensions (leading dots and case normalized internally). |
None
|
allowed_mimetypes
|
set[str] | None
|
Whitelist of MIME types (case-insensitive). |
None
|
verify_magic_bytes
|
bool
|
Sniff the first bytes of each upload
and reject content that mismatches its declared type /
allow-list. Default |
False
|
chunk_size
|
int
|
Stream read chunk in bytes. Default 1 MiB. |
1024 * 1024
|
Raises:
| Type | Description |
|---|---|
ImportError
|
When the required extra ( |
validate
¶
Validate extension and MIME before reading the stream.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file
|
UploadFile
|
The FastAPI upload to validate. |
required |
Raises:
| Type | Description |
|---|---|
InvalidFileTypeException
|
If the extension or MIME type is not in the configured whitelist. |
save
async
¶
save(
file: UploadFile,
*,
subdir: str = "",
filename: str | None = None,
keep_original_name: bool = False,
content_validator: Callable[[bytes], bool] | None = None,
) -> Path
Validate and persist file to the configured backend.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file
|
UploadFile
|
The FastAPI upload. |
required |
subdir
|
str
|
Optional sub-directory / key prefix. |
''
|
filename
|
str | None
|
Explicit final filename (sanitized to
its basename). Takes precedence over |
None
|
keep_original_name
|
bool
|
Preserve the original filename when
|
False
|
content_validator
|
Callable[[bytes], bool] | None
|
Optional
predicate run on the first chunk; |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
Path |
Path
|
|
Path
|
meth: |
Raises:
| Type | Description |
|---|---|
InvalidFileTypeException
|
On a whitelist / content violation. |
FileTooLargeException
|
If the stream exceeds |
replace
async
¶
replace(
old_key: Path | str | None,
file: UploadFile,
*,
subdir: str = "",
filename: str | None = None,
keep_original_name: bool = False,
content_validator: Callable[[bytes], bool] | None = None,
) -> Path
Save a new object and delete the one it replaces.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
old_key
|
Path | str | None
|
Key of the object being replaced;
|
required |
file
|
UploadFile
|
The new FastAPI upload. |
required |
subdir
|
str
|
Optional sub-directory / key prefix. |
''
|
filename
|
str | None
|
Explicit final filename. Same rules as
:meth: |
None
|
keep_original_name
|
bool
|
Preserve the upload's original
filename when |
False
|
content_validator
|
Callable[[bytes], bool] | None
|
Optional
first-chunk predicate; see :meth: |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
Path |
Path
|
|
Raises:
| Type | Description |
|---|---|
InvalidFileTypeException
|
If validation rejects the new file (the old object is left intact). |
FileTooLargeException
|
If the new stream exceeds
|
delete
async
¶
Delete a previously saved object via the shared backend.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
Path | str
|
The storage key returned by :meth: |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
|
bool
|
when it was already missing. |
Raises:
| Type | Description |
|---|---|
InvalidFileTypeException
|
Local backend, when |
exists
async
¶
Return whether an object lives at key.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
Path | str
|
The storage key. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
|
download
async
¶
download(
key: str,
*,
subdir: str = "",
filename: str | None = None,
media_type: str | None = None,
as_attachment: bool = True,
request: Request | None = None,
cache_control: str | None = None,
headers: dict[str, str] | None = None,
) -> Response
Build a download response for key from the configured backend.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
File path (local, relative to the base dir) or object key (MinIO). |
required |
subdir
|
str
|
Optional sub-directory / key prefix. |
''
|
filename
|
str | None
|
Name presented to the client. Defaults to
the basename of |
None
|
media_type
|
str | None
|
MIME type. Guessed/derived when omitted. |
None
|
as_attachment
|
bool
|
|
True
|
request
|
Request | None
|
The incoming request. MinIO mode needs
it to answer |
None
|
cache_control
|
str | None
|
|
None
|
headers
|
dict[str, str] | None
|
Extra response headers. One named like a download security default replaces that default. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
Response |
Response
|
A |
Response
|
(MinIO) ready to return from a router. |
Raises:
| Type | Description |
|---|---|
NotFoundException
|
Local mode, when the path escapes the base directory or the file is missing. |
S3Error
|
MinIO mode, when the object is missing. |
file_response
¶
file_response(
relative_path: Path | str,
*,
subdir: str = "",
filename: str | None = None,
media_type: str | None = None,
as_attachment: bool = True,
headers: dict[str, str] | None = None,
) -> FileResponse
Build a FileResponse streaming a file from local disk.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
relative_path
|
Path | str
|
Path to the file, relative to the base directory (resolved safely). |
required |
subdir
|
str
|
Optional sub-directory under the base directory. |
''
|
filename
|
str | None
|
Name presented to the client. Defaults to the file's own basename. |
None
|
media_type
|
str | None
|
MIME type. Guessed from the filename when omitted. |
None
|
as_attachment
|
bool
|
|
True
|
headers
|
dict[str, str] | None
|
Extra response headers. One named like a download security default replaces that default. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
FileResponse |
FileResponse
|
The response to return from a router. |
Raises:
| Type | Description |
|---|---|
NotFoundException
|
If the file cannot be located. |
RuntimeError
|
When this store is MinIO-backed — use
:meth: |
stream
¶
stream(
content: bytes | Iterable[bytes] | AsyncIterable[bytes],
*,
filename: str,
media_type: str | None = None,
as_attachment: bool = True,
headers: dict[str, str] | None = None,
) -> StreamingResponse
Build a StreamingResponse from in-memory bytes or a generator.
Use for payloads produced on the fly (a generated report, an in-memory zip) rather than read from storage.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
content
|
bytes | Iterable[bytes] | AsyncIterable[bytes]
|
The
payload. Raw |
required |
filename
|
str
|
Name presented to the client. |
required |
media_type
|
str | None
|
MIME type. Guessed from |
None
|
as_attachment
|
bool
|
|
True
|
headers
|
dict[str, str] | None
|
Extra response headers. One named like a download security default replaces that default. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
StreamingResponse |
StreamingResponse
|
The response to return from a router. |
resolve
¶
Resolve a client-supplied path safely under the local base dir.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
relative_path
|
Path | str
|
Path relative to the base directory
(absolute inputs and escaping |
required |
subdir
|
str
|
Optional sub-directory between the base directory
and |
''
|
Returns:
| Name | Type | Description |
|---|---|---|
Path |
Path
|
The resolved, existing file path. |
Raises:
| Type | Description |
|---|---|
NotFoundException
|
If the path escapes the base directory, does not exist, or is not a regular file. |
RuntimeError
|
When this store is MinIO-backed — use
:meth: |
presigned_get_url
async
¶
presigned_get_url(
key: str, *, bucket: str | None = None, expires: timedelta = timedelta(hours=1)
) -> str | None
Return a presigned GET URL, or None for the local backend.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
The object key. |
required |
bucket
|
str | None
|
Target bucket. |
None
|
expires
|
timedelta
|
URL lifetime. Default 1 hour. |
timedelta(hours=1)
|
Returns:
| Type | Description |
|---|---|
str | None
|
str | None: A signed download URL, or |
str | None
|
cannot mint one (local disk). |
presigned_put_url
async
¶
presigned_put_url(
key: str, *, bucket: str | None = None, expires: timedelta = timedelta(minutes=15)
) -> str | None
Return a presigned PUT URL, or None for the local backend.
Lets the client upload directly to MinIO / S3 without streaming the bytes through the API.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
The object key to upload to. |
required |
bucket
|
str | None
|
Target bucket. |
None
|
expires
|
timedelta
|
URL lifetime. Default 15 minutes. |
timedelta(minutes=15)
|
Returns:
| Type | Description |
|---|---|
str | None
|
str | None: A signed upload URL, or |
str | None
|
cannot mint one (local disk). |
MetricsUtils
¶
Aggregated CPU/RAM/disk/GPU readings for the current host.
Built on top of :mod:psutil (always required by the [metrics]
extra) and pynvml (optional — NVIDIA GPU support degrades to
an empty list when the library is missing or no NVIDIA device is
present).
Every method has a synchronous and an asynchronous variant. Sync
methods call :mod:psutil directly (most calls are non-blocking
or block briefly for sampling); async variants run the same code
via :func:asyncio.to_thread so they never stall the event loop
when a longer sampling interval is requested.
Stateless — instantiation is unnecessary; every method is a classmethod.
cpu
classmethod
¶
cpu(*, interval: float = 0.1) -> CPUMetrics
Sample CPU usage.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
interval
|
float
|
Sampling window in seconds. |
0.1
|
Returns:
| Name | Type | Description |
|---|---|---|
CPUMetrics |
CPUMetrics
|
The sampled metrics. |
cpu_async
async
classmethod
¶
cpu_async(*, interval: float = 0.1) -> CPUMetrics
Asyncio-friendly wrapper around :meth:cpu.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
interval
|
float
|
Sampling window in seconds. |
0.1
|
Returns:
| Name | Type | Description |
|---|---|---|
CPUMetrics |
CPUMetrics
|
The sampled metrics. |
memory
classmethod
¶
memory() -> MemoryMetrics
Sample RAM usage.
Returns:
| Name | Type | Description |
|---|---|---|
MemoryMetrics |
MemoryMetrics
|
The current memory snapshot. |
memory_async
async
classmethod
¶
memory_async() -> MemoryMetrics
Asyncio-friendly wrapper around :meth:memory.
Returns:
| Name | Type | Description |
|---|---|---|
MemoryMetrics |
MemoryMetrics
|
The current memory snapshot. |
disk
classmethod
¶
disk(path: str = '/') -> DiskMetrics
Sample disk usage for path.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
The filesystem path to inspect. Defaults to the root partition. |
'/'
|
Returns:
| Name | Type | Description |
|---|---|---|
DiskMetrics |
DiskMetrics
|
The usage snapshot. |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
When |
disk_async
async
classmethod
¶
disk_async(path: str = '/') -> DiskMetrics
Asyncio-friendly wrapper around :meth:disk.
Same error semantics as the sync method — an unreadable path
raises. That is the difference from calling
disks_async([path]), which logs and skips: on a metrics
endpoint a skipped path answers 200 with the disk block simply
absent, and a dashboard cannot tell a mount that vanished from a
disk that was never asked for.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
The filesystem path to inspect. Defaults to the root partition. |
'/'
|
Returns:
| Name | Type | Description |
|---|---|---|
DiskMetrics |
DiskMetrics
|
The usage snapshot. |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
When |
PermissionError
|
When |
disks
classmethod
¶
disks(paths: list[str] | None = None, *, strict: bool = False) -> list[DiskMetrics]
Sample usage for multiple disks.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
paths
|
list[str] | None
|
Paths to inspect. |
None
|
strict
|
bool
|
When |
False
|
Returns:
| Type | Description |
|---|---|
list[DiskMetrics]
|
list[DiskMetrics]: One entry per resolvable path; paths that |
list[DiskMetrics]
|
raise are logged and skipped unless |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
Under |
PermissionError
|
Under |
disks_async
async
classmethod
¶
disks_async(
paths: list[str] | None = None, *, strict: bool = False
) -> list[DiskMetrics]
Asyncio-friendly wrapper around :meth:disks.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
paths
|
list[str] | None
|
Paths to inspect. |
None
|
strict
|
bool
|
Propagate the first failure instead of logging and skipping it. |
False
|
Returns:
| Type | Description |
|---|---|
list[DiskMetrics]
|
list[DiskMetrics]: The collected snapshots. |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
Under |
PermissionError
|
Under |
gpus
classmethod
¶
gpus() -> list[GPUMetrics]
Sample NVIDIA GPU usage via pynvml when available.
Returns an empty list (without raising) when:
pynvmlis not installed,- the NVML library cannot be loaded (no NVIDIA driver, WSL without compute, etc.), or
- no NVIDIA devices are present.
Returns:
| Type | Description |
|---|---|
list[GPUMetrics]
|
list[GPUMetrics]: One entry per detected GPU. |
gpus_async
async
classmethod
¶
gpus_async() -> list[GPUMetrics]
Asyncio-friendly wrapper around :meth:gpus.
Returns:
| Type | Description |
|---|---|
list[GPUMetrics]
|
list[GPUMetrics]: One entry per detected GPU. |
snapshot
classmethod
¶
snapshot(
*, disk_paths: list[str] | None = None, cpu_interval: float = 0.1
) -> SystemMetrics
Build a full :class:SystemMetrics snapshot.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
disk_paths
|
list[str] | None
|
Disks to inspect. |
None
|
cpu_interval
|
float
|
CPU sampling window. |
0.1
|
Returns:
| Name | Type | Description |
|---|---|---|
SystemMetrics |
SystemMetrics
|
The combined snapshot. |
snapshot_async
async
classmethod
¶
snapshot_async(
*, disk_paths: list[str] | None = None, cpu_interval: float = 0.1
) -> SystemMetrics
Asyncio-friendly wrapper around :meth:snapshot.
Runs every sub-collector concurrently via :func:asyncio.gather
so the wall-clock cost is bounded by the slowest sample
(typically CPU).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
disk_paths
|
list[str] | None
|
Disks to inspect. |
None
|
cpu_interval
|
float
|
CPU sampling window. |
0.1
|
Returns:
| Name | Type | Description |
|---|---|---|
SystemMetrics |
SystemMetrics
|
The combined snapshot. |
LogUtils
¶
LogUtils(
name: str,
*,
level: str | int = "INFO",
json_output: bool = True,
log_dir: str | Path | None = "logs",
stdout: bool = True,
file_output: bool = True,
max_bytes: int = DEFAULT_LOG_MAX_BYTES,
backup_count: int = DEFAULT_LOG_BACKUP_COUNT,
rotate_when: str | None = None,
rotate_interval: int = 1,
scope: Literal["root", "logger"] = "root",
)
High-level logging facade used across SDK consumers.
Wraps :func:tempest_fastapi_sdk.configure_logging so callers can
obtain a fully configured JSON logger with one line, and exposes
structured info/warning/error/debug/exception
methods that forward **fields as top-level keys on the JSON
payload via Python's logging.LogRecord.extra.
The class can be used in two flavors:
- Instance API — keeps a configured logger as state and exposes level methods directly. Recommended for service-wide singletons.
- Static helpers — :meth:
configureand :meth:get_loggerfor ad-hoc configuration without tying state to an object.
Attributes:
| Name | Type | Description |
|---|---|---|
logger |
Logger
|
The configured stdlib logger. |
name |
str
|
The logger name. |
Configure and bind a logger to this instance.
Mirrors :func:configure_logging defaults — stdout and file
output are enabled out of the box, writing under logs/.
scope="root" is what makes LogUtils(__name__) safe to
write in every module, which is how the class reads and how it
gets used. The handlers land on the root logger, once per
process, and each module's logger propagates into them. Under
the old per-logger behavior a service with N modules opened N
stdout handlers and N * 6 file handlers on the same six
paths, with that many RotatingFileHandler instances racing
to roll one file over.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Logger name. Typically |
required |
level
|
str | int
|
Minimum log level to emit. Accepts
stdlib names ( |
'INFO'
|
json_output
|
bool
|
When |
True
|
log_dir
|
str | Path | None
|
Directory for per-level files.
Defaults to |
'logs'
|
stdout
|
bool
|
Attach the stdout handler. Defaults to
|
True
|
file_output
|
bool
|
Attach the per-level + |
True
|
max_bytes
|
int
|
Size at which each file rotates. |
DEFAULT_LOG_MAX_BYTES
|
backup_count
|
int
|
Rotated files kept per level. |
DEFAULT_LOG_BACKUP_COUNT
|
rotate_when
|
str | None
|
Rotate by time instead of size
( |
None
|
rotate_interval
|
int
|
Units of |
1
|
scope
|
Literal['root', 'logger']
|
Which logger receives the
handlers. |
'root'
|
configure
staticmethod
¶
configure(
level: str | int = "INFO",
*,
json_output: bool = True,
logger_name: str | None = None,
log_dir: str | Path | None = "logs",
stdout: bool = True,
file_output: bool = True,
max_bytes: int = DEFAULT_LOG_MAX_BYTES,
backup_count: int = DEFAULT_LOG_BACKUP_COUNT,
rotate_when: str | None = None,
rotate_interval: int = 1,
) -> Logger
Imperative shortcut for :func:configure_logging.
Forwards every keyword to :func:configure_logging so the two
share defaults — stdout and file output enabled, logs/
directory used unless overridden.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
level
|
str | int
|
Minimum log level. |
'INFO'
|
json_output
|
bool
|
Emit JSON when |
True
|
logger_name
|
str | None
|
Target logger; |
None
|
log_dir
|
str | Path | None
|
Directory for per-level files.
Defaults to |
'logs'
|
stdout
|
bool
|
Attach the stdout handler. Defaults to
|
True
|
file_output
|
bool
|
Attach the per-level + |
True
|
max_bytes
|
int
|
Size at which each file rotates. |
DEFAULT_LOG_MAX_BYTES
|
backup_count
|
int
|
Rotated files kept per level. |
DEFAULT_LOG_BACKUP_COUNT
|
rotate_when
|
str | None
|
Rotate by time instead of size;
|
None
|
rotate_interval
|
int
|
Units of |
1
|
Returns:
| Type | Description |
|---|---|
Logger
|
logging.Logger: The configured logger. |
get_logger
staticmethod
¶
Return the stdlib logger named name without reconfiguring.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The logger name. |
required |
Returns:
| Type | Description |
|---|---|
Logger
|
logging.Logger: The (possibly unconfigured) logger. |
current_request_id
staticmethod
¶
Return the current request ID from the contextvar.
Useful when callers want to surface the correlation ID outside the log line (e.g. in an HTTP response body).
Returns:
| Type | Description |
|---|---|
str | None
|
str | None: The active request ID, or |
info
¶
info(
message: str,
*args: Any,
stacklevel: int = 2,
exc_info: bool | Literal["auto"] = False,
**fields: Any,
) -> None
Emit an INFO record.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message
|
str
|
The log message, or a |
required |
*args
|
Any
|
Positional arguments for |
()
|
stacklevel
|
int
|
How many frames to walk back when resolving
|
2
|
exc_info
|
bool | Literal['auto']
|
Whether to attach the
current traceback. |
False
|
**fields
|
Any
|
Extra structured fields merged into the JSON
payload. A key that shadows a |
{}
|
Raises:
| Type | Description |
|---|---|
TypeError
|
When a field name is reserved by |
debug
¶
debug(
message: str,
*args: Any,
stacklevel: int = 2,
exc_info: bool | Literal["auto"] = False,
**fields: Any,
) -> None
Emit a DEBUG record.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message
|
str
|
The log message, or a |
required |
*args
|
Any
|
Positional arguments for |
()
|
stacklevel
|
int
|
How many frames to walk back when resolving
|
2
|
exc_info
|
bool | Literal['auto']
|
Whether to attach the
current traceback. |
False
|
**fields
|
Any
|
Extra structured fields merged into the JSON
payload. A key that shadows a |
{}
|
Raises:
| Type | Description |
|---|---|
TypeError
|
When a field name is reserved by |
warning
¶
warning(
message: str,
*args: Any,
stacklevel: int = 2,
exc_info: bool | Literal["auto"] = False,
**fields: Any,
) -> None
Emit a WARNING record.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message
|
str
|
The log message, or a |
required |
*args
|
Any
|
Positional arguments for |
()
|
stacklevel
|
int
|
How many frames to walk back when resolving
|
2
|
exc_info
|
bool | Literal['auto']
|
Whether to attach the
current traceback. |
False
|
**fields
|
Any
|
Extra structured fields merged into the JSON
payload. A key that shadows a |
{}
|
Raises:
| Type | Description |
|---|---|
TypeError
|
When a field name is reserved by |
error
¶
error(
message: str,
*args: Any,
stacklevel: int = 2,
exc_info: bool | Literal["auto"] = False,
**fields: Any,
) -> None
Emit an ERROR record.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message
|
str
|
The log message, or a |
required |
*args
|
Any
|
Positional arguments for |
()
|
stacklevel
|
int
|
How many frames to walk back when resolving
|
2
|
exc_info
|
bool | Literal['auto']
|
Whether to attach the
current traceback. |
False
|
**fields
|
Any
|
Extra structured fields merged into the JSON
payload. A key that shadows a |
{}
|
Raises:
| Type | Description |
|---|---|
TypeError
|
When a field name is reserved by |
error_500
¶
Emit an ERROR record routed to the dedicated 500.log.
configure_logging writes a 500.log and filters it on the
:data:~tempest_fastapi_sdk.core.logging.HTTP_500_MARKER extra,
but the only things that set that marker are this SDK's own
exception handlers — so a service reporting a grave failure of
its own had to import a private-looking constant from
core.logging to reach a file the SDK already writes for it.
The record also lands in error.log like any other ERROR. The
isolated file exists so grave failures are not buried among the
rest, not to remove them from the level stream.
The traceback is attached whenever one is being handled, since a 500 that reports no traceback is the case the file exists for.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message
|
str
|
The log message, or a |
required |
*args
|
Any
|
Positional arguments for |
()
|
stacklevel
|
int
|
How many frames to walk back when resolving
|
2
|
**fields
|
Any
|
Extra structured fields. A |
{}
|
Raises:
| Type | Description |
|---|---|
TypeError
|
When a field name is reserved by |
critical
¶
critical(
message: str,
*args: Any,
stacklevel: int = 2,
exc_info: bool | Literal["auto"] = False,
**fields: Any,
) -> None
Emit a CRITICAL record.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message
|
str
|
The log message, or a |
required |
*args
|
Any
|
Positional arguments for |
()
|
stacklevel
|
int
|
How many frames to walk back when resolving
|
2
|
exc_info
|
bool | Literal['auto']
|
Whether to attach the
current traceback. |
False
|
**fields
|
Any
|
Extra structured fields merged into the JSON
payload. A key that shadows a |
{}
|
Raises:
| Type | Description |
|---|---|
TypeError
|
When a field name is reserved by |
exception
¶
Emit an ERROR record with the current exception traceback.
Must be called from inside an except block — the traceback
is attached unconditionally, and True outside an except
writes NoneType: None. Use error(..., exc_info="auto")
for a call site that is sometimes inside one.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message
|
str
|
The log message, or a |
required |
*args
|
Any
|
Positional arguments for |
()
|
stacklevel
|
int
|
How many frames to walk back when resolving
|
2
|
**fields
|
Any
|
Extra structured fields merged into the JSON
payload. A key that shadows a |
{}
|
Raises:
| Type | Description |
|---|---|
TypeError
|
When a field name is reserved by |
AttemptThrottle
¶
AttemptThrottle(
backend: ThrottleBackend,
*,
max_attempts: int,
window_seconds: int,
namespace: str = "throttle",
fail_open: bool = True,
)
Fixed-window failure counter over an injected async KV backend.
Initialize the throttle.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
backend
|
ThrottleBackend
|
Async KV store (e.g.
|
required |
max_attempts
|
int
|
Failures allowed before a key is
blocked. Must be |
required |
window_seconds
|
int
|
Sliding window length (also the TTL
applied on the first failure). Must be |
required |
namespace
|
str
|
Key prefix so multiple throttles can share a backend without colliding. |
'throttle'
|
fail_open
|
bool
|
When |
True
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
status
async
¶
status(key: str) -> ThrottleStatus
Read the current status for key without mutating it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
The domain key (e.g. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
ThrottleStatus |
ThrottleStatus
|
Current attempts / blocked state. On a
backend error with |
hit
async
¶
hit(key: str) -> ThrottleStatus
Record one failure for key and return the new status.
Increments the counter and, on the first failure of a window, applies the TTL so the window expires on its own.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
The domain key. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
ThrottleStatus |
ThrottleStatus
|
Status after the increment. On a backend
error with |
reset
async
¶
Clear the counter for key (e.g. after a success).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
The domain key. |
required |
reserve
async
¶
reserve(
key: str,
*,
message: str | None = None,
exception: type[TooManyRequestsException] = TooManyRequestsException,
) -> ThrottleStatus
Take one attempt from key's budget before verifying it.
The increment is the check: the backend's atomic INCR hands each
concurrent caller a distinct count, so at most max_attempts
callers per window get past this line however many arrive at once.
Use it instead of :meth:raise_if_blocked followed by a later
:meth:hit, which only bounds sequential attempts.
The reserved slot stays spent when the attempt fails. When it turns
out not to be a failure (a successful login), either clear the key
with :meth:reset or give back just this slot with :meth:release.
A refused reservation is counted too, so a key that keeps trying
while blocked stays blocked until the window ends.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
The domain key. |
required |
message
|
str | None
|
Optional override for the 429 message. |
None
|
exception
|
type[TooManyRequestsException]
|
The class to raise. |
TooManyRequestsException
|
Returns:
| Name | Type | Description |
|---|---|---|
ThrottleStatus |
ThrottleStatus
|
The status after the reservation, when it fits |
ThrottleStatus
|
the budget. On a backend error with |
|
ThrottleStatus
|
unblocked status. |
Raises:
| Type | Description |
|---|---|
TooManyRequestsException
|
When the reservation exceeds
|
release
async
¶
Give back one slot taken by :meth:reserve.
Decrements the counter when the backend offers decr (Redis and
:class:InMemoryThrottleBackend do). A counter that reaches zero, or
a key that expired in between, is deleted rather than left behind
without a TTL. A backend without decr keeps the slot spent,
which errs towards throttling.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
The domain key. |
required |
raise_if_blocked
async
¶
raise_if_blocked(
key: str,
*,
message: str | None = None,
exception: type[TooManyRequestsException] = TooManyRequestsException,
) -> ThrottleStatus
Raise :class:TooManyRequestsException when key is blocked.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
The domain key. |
required |
message
|
str | None
|
Optional override for the 429 message. |
None
|
exception
|
type[TooManyRequestsException]
|
The class to raise —
a subclass carrying its own |
TooManyRequestsException
|
This only reads the counter. Paired with a :meth:hit after a
slow verification it does not bound concurrent attempts; use
:meth:reserve for that.
Returns:
| Name | Type | Description |
|---|---|---|
ThrottleStatus |
ThrottleStatus
|
The (unblocked) status when within budget. |
Raises:
| Type | Description |
|---|---|
TooManyRequestsException
|
When the attempt budget for |
InMemoryThrottleBackend
¶
Process-local :class:ThrottleBackend — no Redis, no network.
Holds one (count, expires_at) pair per key in a dict and serves the
five async verbs :class:AttemptThrottle calls, with the same return
contract Redis has: ttl answers -2 for an absent key and -1
for one carrying no TTL.
The counter lives in the process that served the request.
Two workers each keep their own dict, so the budget an account
can reach is max_attempts * workers: the bound holds per
worker, not per account. Anything served by more than one
process (uvicorn --workers, gunicorn, more than one pod) needs a
shared backend; pass the Redis client to
:class:AttemptThrottle there. Correct for a single-process
deployment, a dev server, and tests.
Every incr first drops the entries whose TTL already passed, so the
dict stays bounded by the keys touched inside one window and a key
nobody touches again does not live as long as the process.
Example
backend = InMemoryThrottleBackend() throttle = AttemptThrottle(backend, max_attempts=5, window_seconds=900) await throttle.hit("mfa:user-id") ThrottleStatus(attempts=1, blocked=False, retry_after_seconds=0)
Initialize an empty backend.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
clock
|
Callable[[], float]
|
Zero-argument callable returning
the current time in seconds. Defaults to
:func: |
monotonic
|
incr
async
¶
Atomically increment name and return the new count.
The first increment of a window creates the key with no TTL, exactly
like Redis INCR — the caller is the one that follows up with
:meth:expire.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Identifier being throttled (an IP, a user, an email). |
required |
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
The attempt count after the increment. |
decr
async
¶
Decrement name and return the new count, like Redis DECR.
An absent or expired key starts from zero, so the result is -1
with no TTL, exactly as Redis answers; :meth:AttemptThrottle.release
deletes such a key.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Identifier being throttled (an IP, a user, an email). |
required |
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
The attempt count after the decrement. |
expire
async
¶
Set a TTL (seconds) on name.
A key that is absent or already expired is left absent, which is
what EXPIRE does.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Identifier being throttled (an IP, a user, an email). |
required |
seconds
|
int
|
Window length in seconds. |
required |
ttl
async
¶
Return remaining TTL in seconds (-1/-2 when unset).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Identifier being throttled (an IP, a user, an email). |
required |
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
|
int
|
TTL, and otherwise the seconds left, rounded up — a key |
|
int
|
that is still alive never answers |
|
int
|
reads as "no TTL" and would replace with the full window. |
get
async
¶
Return the counter at name as text.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Identifier being throttled (an IP, a user, an email). |
required |
Returns:
| Type | Description |
|---|---|
str | bytes | None
|
str | bytes | None: The attempt count as a decimal string, or |
str | bytes | None
|
|
str | bytes | None
|
ever parses it as an |
delete
async
¶
Delete name, whether or not it was there.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Identifier being throttled (an IP, a user, an email). |
required |
sign_path
¶
sign_path(
path: str,
*,
secret: str,
expires_in: timedelta,
purpose: str,
now: datetime | None = None,
) -> str
Return path signed for purpose and valid for expires_in.
Call it where the caller has already been authorized — typically in the mapper that turns a stored key into the response schema — so only an allowed caller ever holds the URL.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
The route path, decoded, exactly as the route will see
it in |
required |
secret
|
str
|
The application secret. Domain separation makes reusing
|
required |
expires_in
|
timedelta
|
How long the URL stays valid. Must be positive. |
required |
purpose
|
str
|
Label binding the signature to one use ( |
required |
now
|
datetime | None
|
The signing instant. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The percent-encoded path followed by |
str
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
verify_path
¶
verify_path(
path: str,
*,
expires: int,
signature: str,
secret: str,
purpose: str,
now: datetime | None = None,
) -> None
Check that signature authorizes path until expires.
The signature is checked first and the expiry second, so a forged
expires is reported as invalid, not as expired. A URL stops being
valid at the expires second itself.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
The decoded request path — |
required |
expires
|
int
|
The |
required |
signature
|
str
|
The |
required |
secret
|
str
|
The secret the URL was signed with. |
required |
purpose
|
str
|
The purpose the URL was signed for. |
required |
now
|
datetime | None
|
The verification instant. |
None
|
Raises:
| Type | Description |
|---|---|
InvalidSignedURLException
|
|
ExpiredSignedURLException
|
|
ValueError
|
If |
VAPID_SUBJECT_PATTERN
module-attribute
¶
VAPID_SUBJECT_PATTERN: Final[str] = (
"^(mailto:.+@((localhost|[%\\w-]+(\\.[%\\w-]+)+|([0-9a-f]{1,4}):+([0-9a-f]{1,4})?)))|https:\\/\\/(localhost|[\\w-]+\\.[\\w\\.-]+|([0-9a-f]{1,4}:+)+([0-9a-f]{1,4})?)$"
)
The pattern a VAPID sub must match, matched case-insensitively.
Ported from py_vapid 1.9.4's _check_sub, character for character, so
what passes here is exactly what the signature accepts. Its quirk is ported
too: the trailing $ anchors only the https:// branch, so a
mailto: address may be followed by anything. tests/utils/test_vapid.py
compares this string with the installed py_vapid source, so an upstream
change fails a test instead of drifting.
check_vapid_subject
¶
Refuse a sub claim py_vapid would not sign with.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
subject
|
str
|
The candidate |
required |
name
|
str
|
What the value is called in the message (the setting or the argument). |
'VAPID_SUBJECT'
|
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
is_valid_vapid_subject
¶
Return whether py_vapid would sign with this sub claim.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
subject
|
str
|
The candidate |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
|
SIGNED_URL_EXPIRES_PARAM
module-attribute
¶
Query parameter carrying the expiry, in unix seconds.
SIGNED_URL_SIGNATURE_PARAM
module-attribute
¶
Query parameter carrying the URL-safe base64 HMAC-SHA256.
UFEnum
¶
Bases: StrEnum
The 27 Brazilian federative units, keyed by their acronym.
RegionEnum
¶
Bases: StrEnum
The five official IBGE macro-regions of Brazil.
StateBR
¶
Bases: BaseModel
A Brazilian federative unit and its municipalities.
Attributes:
| Name | Type | Description |
|---|---|---|
uf |
UFEnum
|
The federative unit acronym (e.g. |
name |
str
|
The full state name (e.g. |
region |
RegionEnum
|
The IBGE macro-region the state belongs to. |
cities |
list[str]
|
The municipality names, alphabetically sorted, in canonical proper case. |
CityBR
¶
Bases: BaseModel
A single Brazilian municipality.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
str
|
The municipality name in canonical proper case
(e.g. |
uf |
UFEnum
|
The federative unit the municipality belongs to. |
list_states
¶
list_states() -> list[StateBR]
Return every Brazilian state ordered by acronym.
Returns:
| Type | Description |
|---|---|
list[StateBR]
|
list[StateBR]: All 27 federative units with their cities. |
get_state
¶
Return the :class:StateBR for a given federative unit.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
uf
|
str | UFEnum
|
The acronym (case-insensitive) or :class: |
required |
Returns:
| Name | Type | Description |
|---|---|---|
StateBR |
StateBR
|
The matching state, including its municipalities. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
cities_by_uf
¶
cities_by_uf(uf: str | UFEnum) -> list[str]
Return the alphabetically sorted municipalities of a state.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
uf
|
str | UFEnum
|
The acronym (case-insensitive) or :class: |
required |
Returns:
| Type | Description |
|---|---|
list[str]
|
list[str]: The municipality names in canonical proper case. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
states_by_region
¶
states_by_region(region: RegionEnum) -> list[StateBR]
Return every state belonging to a given macro-region.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
region
|
RegionEnum
|
The IBGE macro-region to filter by. |
required |
Returns:
| Type | Description |
|---|---|
list[StateBR]
|
list[StateBR]: The states in that region, ordered by acronym. |
is_valid_uf
¶
Check whether value is a valid federative unit acronym.
The match is case-insensitive and ignores surrounding whitespace,
so "sp" and " SP " are both accepted.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
str
|
The acronym to inspect. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
|
normalize_uf
¶
normalize_uf(value: str) -> UFEnum
Validate value and return the matching :class:UFEnum.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
str
|
The acronym (any case, optional whitespace). |
required |
Returns:
| Name | Type | Description |
|---|---|---|
UFEnum |
UFEnum
|
The federative unit enum member. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
is_valid_city
¶
is_valid_city(uf: str | UFEnum, city: str) -> bool
Check whether city exists in the given federative unit.
Matching ignores accents, letter case and surrounding whitespace,
so "sao paulo" matches "São Paulo".
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
uf
|
str | UFEnum
|
The acronym (case-insensitive) or :class: |
required |
city
|
str
|
The municipality name to look up. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
|
bool
|
|
normalize_city
¶
normalize_city(uf: str | UFEnum, city: str) -> str
Validate city against uf and return its canonical name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
uf
|
str | UFEnum
|
The acronym (case-insensitive) or :class: |
required |
city
|
str
|
The municipality name (any case/accents). |
required |
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The canonical proper-case municipality name. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
uf_choices
¶
uf_choices() -> list[ChoiceBR]
Return every federative unit as a frontend <select> choice.
Each choice carries the acronym as value (what you store/submit,
and what :data:UFField validates) and the full state name as
label. Ordered by acronym.
Returns:
| Type | Description |
|---|---|
list[ChoiceBR]
|
list[ChoiceBR]: One choice per state, e.g. |
list[ChoiceBR]
|
|
region_choices
¶
region_choices() -> list[ChoiceBR]
Return every IBGE macro-region as a frontend <select> choice.
Both value and label carry the region name (e.g. "Sudeste")
since that is the stored :class:RegionEnum value.
Returns:
| Type | Description |
|---|---|
list[ChoiceBR]
|
list[ChoiceBR]: One choice per macro-region, ordered as declared. |
city_choices
¶
Return the cities of a federative unit as <select> choices.
Each choice uses the canonical city name for both value and
label. Ordered alphabetically.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
uf
|
str | UFEnum
|
The acronym (case-insensitive) or :class: |
required |
Returns:
| Type | Description |
|---|---|
list[ChoiceBR]
|
list[ChoiceBR]: One choice per municipality. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
parse_currency_br
¶
Read an amount printed in Brazilian notation into an exact Decimal.
Accepts both separator conventions, because a source that transcribes a Brazilian document sometimes normalizes to the US one:
"R$ 2.930,00"/"2.930,00"— comma decimal, dot thousands"2930.00"/"2,930.00"— dot decimal, the US convention"2930"— no separator at all
The last separator present decides which one is decimal. The one
genuinely ambiguous case is a lone dot followed by exactly three digits:
"2.930" is read as two thousand nine hundred and thirty, never as
two point nine three, because that is what the notation means in the
documents this parses. Pass the US form with its own thousands
separator ("2,930.00") when the other reading is intended.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
The printed amount, with or without symbol and spaces. |
required |
Returns:
| Type | Description |
|---|---|
Decimal | None
|
Decimal | None: The parsed amount, or |
Decimal | None
|
no digit at all. |
Decimal | None
|
not print a price" distinguishable from "the document printed |
Decimal | None
|
R$ 0,00" — a distinction that decides whether a line is missing data |
Decimal | None
|
or is genuinely free of charge. |
format_currency_br
¶
Render an amount in Brazilian currency notation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
amount
|
Decimal
|
The amount to render; quantized to two places before formatting. |
required |
symbol
|
bool
|
Whether to prefix the |
True
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The formatted amount, e.g. |
str
|
amount carries the sign ahead of the symbol ( |
|
str
|
is how a credit reads on a Brazilian statement and how a closing |
|
str
|
difference must appear on a worksheet. |
format_percent_br
¶
Render a ratio as a Brazilian-formatted percentage.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ratio
|
Decimal
|
The ratio to render, where |
required |
places
|
int
|
How many decimal places to keep. |
2
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The formatted percentage, e.g. |
format_quantity_br
¶
Render a non-monetary quantity in Brazilian notation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
amount
|
Decimal
|
The quantity to render. |
required |
places
|
int
|
How many decimal places to keep. |
2
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The formatted quantity, e.g. |
quantize_money
¶
Round a monetary amount to two decimal places, half away from zero.
Uses ROUND_HALF_UP rather than :class:~decimal.Decimal's default
ROUND_HALF_EVEN. Banker's rounding is the better choice for a long
series of independent roundings, but it is not what a Brazilian
accountant, a printed invoice, or a spreadsheet built by hand does —
and a generated document that disagrees with the manual one by a cent
is a document that gets rejected.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
amount
|
Decimal
|
The unrounded amount. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
Decimal |
Decimal
|
The amount quantized to two decimal places. |
CENT
module-attribute
¶
The smallest representable monetary unit; the quantization target.
HUNDRED
module-attribute
¶
Literal one hundred, used to convert ratios to display percentages.
get_client_ip
¶
Resolve the client IP from a Starlette/FastAPI request.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
request
|
Request
|
The inbound request. |
required |
trusted_header
|
str | None
|
Name of the single edge-set header
to trust (case-insensitive, e.g. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The resolved client IP, or |
get_client_ip_from_scope
¶
Resolve the client IP from a raw ASGI scope.
Mirrors :func:get_client_ip for middleware that sees the ASGI
scope directly instead of a Starlette :class:Request.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
scope
|
Scope
|
The ASGI scope. |
required |
trusted_header
|
str | None
|
Name of the single edge-set header
to trust (case-insensitive). |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The resolved client IP, or |
parse_client_ip
¶
Return value as a canonical IP address, or None.
An IPv4-mapped IPv6 address is rendered with the IPv4 part dotted
(::ffff:1.2.3.4) on every Python version. str() of the
address does that only from Python 3.13 on; 3.12 renders the same
address as ::ffff:102:304, so two replicas on different Pythons
keyed one client under two rate-limit buckets.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
str
|
A header value claimed to be one client address. |
required |
Returns:
| Type | Description |
|---|---|
str | None
|
str | None: The canonical form ( |
str | None
|
back to text) after stripping whitespace, or |
str | None
|
value is not exactly one IPv4 or IPv6 address. |
to_utc
¶
Convert a datetime to UTC.
Naive datetimes are assumed to be in UTC and tagged with the UTC tzinfo. Aware datetimes are converted to UTC.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
datetime
|
The datetime to normalize. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
datetime |
datetime
|
A timezone-aware datetime in UTC. |
utcnow
¶
Return the current time as a timezone-aware UTC datetime.
Returns:
| Name | Type | Description |
|---|---|---|
datetime |
datetime
|
The current UTC time. |
modify_dict
¶
modify_dict(
data: dict[str, Any],
exclude: list[str] | None = None,
include: dict[str, Any] | None = None,
) -> dict[str, Any]
Filter and extend a dictionary in a single pass.
Removes any keys listed in exclude and merges the
include mapping on top of the remaining items.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
dict[str, Any]
|
The source dictionary. |
required |
exclude
|
list[str] | None
|
Keys to drop from the output. |
None
|
include
|
dict[str, Any] | None
|
Extra entries to merge into
the output (these win over keys already in |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
dict[str, Any]: A new dictionary with the requested mutations. |
build_content_disposition
¶
build_content_disposition(
filename: str, *, as_attachment: bool = True, media_type: str | None = None
) -> str
Build an RFC 6266 Content-Disposition header value.
Emits both an ASCII filename (with quotes/backslashes stripped as a
legacy fallback) and a UTF-8 filename* parameter (RFC 5987) so
non-ASCII names survive across clients.
The name is treated as untrusted, because in the documented usage it is
UploadFile.filename — a value the client chose. Taking the basename
stops a path from being injected, but on its own left the control
characters in: a name containing \r\n produced a header value with a
real line break, which an ASGI server that does not validate header
values (uvicorn on httptools) writes to the socket verbatim, letting
the caller append headers of their own to your response. Every character
below 0x20 plus DEL is dropped here, so what comes out is always
a single header line.
as_attachment=False is a request, not a decision: it yields
inline only when media_type is in
:data:INLINE_SAFE_MEDIA_TYPES. Any other type — text/html,
image/svg+xml, application/octet-stream — and None yield
attachment.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filename
|
str
|
The name the client should see for the download. Reduced to its basename, with control characters removed, so neither a path nor a header break can be injected. |
required |
as_attachment
|
bool
|
|
True
|
media_type
|
str | None
|
The type the response carries. Parameters
are ignored in the check. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
A ready-to-use header value, e.g. |
str
|
|
BulkEmailReport
dataclass
¶
BulkEmailReport(
delivered: int, permanent: list[FailedRecipient], transient: list[FailedRecipient]
)
What a bulk send actually did.
Split by what the caller should do next, which is the whole point:
5xx means the mailbox does not exist and the address should be
pruned, 4xx means full or greylisted and the message should be
requeued. Collapsing them into one "failed" list forces the caller to
re-parse SMTP codes it already had.
Attributes:
| Name | Type | Description |
|---|---|---|
delivered |
int
|
Messages the server accepted. |
permanent |
list[FailedRecipient]
|
|
transient |
list[FailedRecipient]
|
|
failed
property
¶
Return how many recipients did not receive the message.
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
|
FailedRecipient
dataclass
¶
One address a bulk send could not deliver to.
Attributes:
| Name | Type | Description |
|---|---|---|
email |
str
|
The address that failed. |
code |
int | None
|
SMTP reply code, when the server gave one. |
message |
str
|
The server's reply text, verbatim. |
CentsField
module-attribute
¶
Monetary amount in minor units (cents): a non-negative integer.
Storing money as integer cents avoids binary float rounding. Use this for prices/balances and divide by 100 only at the presentation edge.
DecimalPercentField
module-attribute
¶
Exact percentage in the inclusive range 0..100.
The :class:~decimal.Decimal counterpart of :data:PercentField, for the
same reason as :data:DecimalRatioField. Divide by
:data:~tempest_fastapi_sdk.utils.currency.HUNDRED to reach the ratio.
DecimalRatioField
module-attribute
¶
Exact fraction in the inclusive range 0..1.
The :class:~decimal.Decimal counterpart of :data:RatioField. Use it —
never the float one — wherever the fraction multiplies money.
Decimal("0.28") is exactly twenty-eight percent; 0.28 is not, and
the difference surfaces the moment it meets a :data:PriceField: Python
raises TypeError on Decimal * float, and the "fix" of casting one
side is what moves the cent a bid is judged on.
HexColorField
module-attribute
¶
CSS hex color, 3 or 6 hex digits with a leading # (#fff / #abc123).
LatitudeField
module-attribute
¶
Geographic latitude in degrees, -90..90.
LocaleField
module-attribute
¶
LocaleField = Annotated[LocaleEnum, BeforeValidator(normalize_locale_tag)]
Pydantic type that accepts a loose locale string and yields a :class:LocaleEnum.
The :class:~pydantic.BeforeValidator runs ahead of the enum coercion, so
case and separator variants ("pt_BR", "PT-BR") and the bare primary
subtag ("pt" -> PT_BR) are accepted; an unsupported tag raises a
clear invalid locale error (HTTP 422). Use it on a request schema the
way :data:UFField is used for state — the stored/response value can stay a
plain str.
LongitudeField
module-attribute
¶
Geographic longitude in degrees, -180..180.
NonEmptyStrField
module-attribute
¶
String trimmed of surrounding whitespace, rejected when empty.
Whitespace-only input fails because it is stripped to "" before the
min_length=1 check.
NonNegativeFloatField
module-attribute
¶
Float greater than or equal to zero.
NonNegativeIntField
module-attribute
¶
Integer greater than or equal to zero.
PercentField
module-attribute
¶
Percentage in the inclusive range 0..100.
PortField
module-attribute
¶
TCP/UDP port number in the valid range 1..65535.
PositiveFloatField
module-attribute
¶
Float strictly greater than zero.
PositiveIntField
module-attribute
¶
Integer strictly greater than zero (quantities, counts, 1-based ids).
PriceField
module-attribute
¶
Non-negative monetary amount as a :class:~decimal.Decimal, 2 places.
Prefer :data:CentsField (integer cents) for storage; use PriceField
when an exact decimal with two fractional digits is the contract (e.g. a
payment gateway payload).
RatingField
module-attribute
¶
Star rating as an integer in the inclusive range 0..5.
The canonical 0-to-5-star review score: 0 means "no stars", 5 the
maximum. Use it for a rating column/field so the 0..5 bound lives in
the type instead of a hand-written validator.
RatioField
module-attribute
¶
Fraction/probability in the inclusive range 0..1.
SignedDecimalRatioField
module-attribute
¶
Exact fraction, capped at 1, that may go below zero.
For a derived share that can legitimately come out negative: a balancing line the premises left no slack for, or a closing difference a document must disclose rather than clamp to zero. Bounding it above but not below is deliberate — over 100% is a bug, under 0% is news.
SlugField
module-attribute
¶
URL-safe slug: lowercase alphanumerics in kebab-case (my-post-1).
REQUEST_ID_HEADER
module-attribute
¶
Default outbound header carrying the inbound correlation id.
Override per client with HTTPClient(request_id_header=...).
ChoiceBR
¶
Bases: BaseModel
A value/label pair ready for a frontend <select>.
The shape every dropdown wants: a stable value to store/submit
and a human label to show. Returned by :func:uf_choices,
:func:region_choices and :func:city_choices.
Attributes:
| Name | Type | Description |
|---|---|---|
value |
str
|
The value to store/submit (e.g. the UF acronym
|
label |
str
|
The human-facing text to display (e.g. the full
state name |
CityNameField
module-attribute
¶
Pydantic type for a trimmed city name (no cross-field UF validation).
UFField
module-attribute
¶
UFField = Annotated[UFEnum, BeforeValidator(normalize_uf)]
Pydantic type that accepts any-case acronym and yields a :class:UFEnum.
The :class:~pydantic.BeforeValidator runs ahead of the enum coercion,
so lower-case and whitespace-padded acronyms ("sp", " RJ ") are
accepted and an invalid value raises a clear invalid UFEnum error.
CPUMetrics
dataclass
¶
CPUMetrics(
percent: float,
cores_logical: int,
cores_physical: int,
load_average: tuple[float, float, float] | None = None,
)
CPU usage snapshot.
Attributes:
| Name | Type | Description |
|---|---|---|
percent |
float
|
Aggregate CPU utilization (0-100). |
cores_logical |
int
|
Logical core count (including SMT). |
cores_physical |
int
|
Physical core count. |
load_average |
tuple[float, float, float] | None
|
⅕/15-minute
load averages on POSIX; |
to_dict
¶
Return the metrics as a plain dict.
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
dict[str, Any]: The dataclass fields. |
DiskMetrics
dataclass
¶
Disk usage snapshot for a single mount point.
Attributes:
| Name | Type | Description |
|---|---|---|
path |
str
|
The mount point inspected. |
total_bytes |
int
|
Filesystem total capacity. |
used_bytes |
int
|
Used bytes. |
free_bytes |
int
|
Free bytes. |
percent |
float
|
Used percentage (0-100). |
to_dict
¶
Return the metrics as a plain dict.
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
dict[str, Any]: The dataclass fields. |
GPUMetrics
dataclass
¶
GPUMetrics(
index: int,
name: str,
memory_total_bytes: int,
memory_used_bytes: int,
memory_free_bytes: int,
utilization_percent: float,
temperature_celsius: float | None = None,
)
Single-GPU usage snapshot.
Populated by :func:pynvml (NVIDIA only). Non-NVIDIA hosts get an
empty list from :meth:MetricsUtils.gpus.
Attributes:
| Name | Type | Description |
|---|---|---|
index |
int
|
Device index (0-based). |
name |
str
|
Device model name. |
memory_total_bytes |
int
|
VRAM capacity. |
memory_used_bytes |
int
|
VRAM in use. |
memory_free_bytes |
int
|
VRAM free. |
utilization_percent |
float
|
GPU utilization (0-100). |
temperature_celsius |
float | None
|
Core temperature, when reported by the driver. |
to_dict
¶
Return the metrics as a plain dict.
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
dict[str, Any]: The dataclass fields. |
MemoryMetrics
dataclass
¶
RAM usage snapshot.
Attributes:
| Name | Type | Description |
|---|---|---|
total_bytes |
int
|
Total physical memory. |
used_bytes |
int
|
Memory actively in use. |
available_bytes |
int
|
Memory available for new allocations. |
percent |
float
|
Used percentage (0-100). |
to_dict
¶
Return the metrics as a plain dict.
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
dict[str, Any]: The dataclass fields. |
SystemMetrics
dataclass
¶
SystemMetrics(
cpu: CPUMetrics,
memory: MemoryMetrics,
disks: list[DiskMetrics] = list(),
gpus: list[GPUMetrics] = list(),
)
Full machine snapshot returned by :meth:MetricsUtils.snapshot.
Attributes:
| Name | Type | Description |
|---|---|---|
cpu |
CPUMetrics
|
CPU usage block. |
memory |
MemoryMetrics
|
RAM usage block. |
disks |
list[DiskMetrics]
|
One entry per inspected path. |
gpus |
list[GPUMetrics]
|
One entry per detected NVIDIA GPU. |
to_dict
¶
Return the snapshot as a nested dict ready for JSON.
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
dict[str, Any]: |
generate_opaque_token
¶
Generate a cryptographically random token and its digest.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
nbytes
|
int
|
Entropy in bytes for the URL-safe token. Defaults to 32 (~43 characters), well above brute-force reach. |
_DEFAULT_NBYTES
|
Returns:
| Type | Description |
|---|---|
tuple[str, str]
|
tuple[str, str]: |
hash_opaque_token
¶
Return the SHA-256 hex digest of a token's plaintext.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
plaintext
|
str
|
The token value to hash. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
64-character lowercase hex digest. |
verify_opaque_token
¶
Constant-time check that plaintext hashes to token_hash.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
plaintext
|
str
|
The token submitted by the caller. |
required |
token_hash
|
str
|
The stored SHA-256 hex digest. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
|
CEP_PATTERN
module-attribute
¶
Match a Brazilian CEP in either masked (00000-000) or raw form.
CEPField
module-attribute
¶
CEPField = Annotated[str, AfterValidator(normalize_cep)]
Pydantic field type that validates a Brazilian CEP, normalized to 8 digits.
CNPJ_PATTERN
module-attribute
¶
Match a CNPJ in either masked (00.000.000/0000-00) or raw form.
CNPJField
module-attribute
¶
CNPJField = Annotated[str, AfterValidator(normalize_cnpj)]
Pydantic field type that validates and normalizes a CNPJ to 14 digits.
CPF_CNPJ_PATTERN
module-attribute
¶
CPF_CNPJ_PATTERN: Final[Pattern[str]] = re.compile(
f"(?:{CPF_PATTERN.pattern[1:-1]})|(?:{CNPJ_PATTERN.pattern[1:-1]})"
)
Match either a CPF or a CNPJ (masked or raw).
CPF_PATTERN
module-attribute
¶
Match a CPF in either masked (000.000.000-00) or raw form.
CPFField
module-attribute
¶
CPFField = Annotated[str, AfterValidator(normalize_cpf)]
Pydantic field type that validates and normalizes a CPF to 11 digits.
CPFOrCNPJField
module-attribute
¶
CPFOrCNPJField = Annotated[str, AfterValidator(normalize_cpf_cnpj)]
Pydantic field type that accepts either a CPF or a CNPJ.
detect_pix_key_type
¶
detect_pix_key_type(value: str) -> PixKeyType | None
Return the :class:PixKeyType a PIX key belongs to, or None.
Detection is by shape: @ → e-mail, leading + → phone, UUID
shape → random, otherwise digits-only length + check digits decide
between CPF and CNPJ.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
str
|
The raw PIX key (masked CPF/CNPJ accepted). |
required |
Returns:
| Type | Description |
|---|---|
PixKeyType | None
|
PixKeyType | None: The detected type, or |
PixKeyType | None
|
is not a valid key of any type, including any value longer than |
PixKeyType | None
|
77 characters once trimmed. |
is_valid_cep
¶
Check whether value looks like a Brazilian CEP.
CEPs have no check digits — validation only enforces the
eight-digit shape (with or without the canonical 00000-000
mask). Use the official Correios API for existence checks.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
str
|
The CEP string to inspect. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
|
is_valid_cnpj
¶
Check whether value is a syntactically valid CNPJ.
Accepts both masked (00.000.000/0000-00) and unmasked input.
Sequences with all repeated digits are rejected.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
str
|
The CNPJ string to inspect. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
|
bool
|
has correct check digits. |
is_valid_cpf
¶
Check whether value is a syntactically valid CPF.
Accepts both masked (000.000.000-00) and unmasked input.
Sequences with all repeated digits (e.g. "11111111111") are
rejected even though they pass the modulo math.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
str
|
The CPF string to inspect. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
|
bool
|
has correct check digits. |
is_valid_cpf_cnpj
¶
Check whether value is a valid CPF or CNPJ.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
str
|
The document string to inspect. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
|
or |
bool
|
func: |
is_valid_mobile_phone_br
¶
Check whether value is a Brazilian mobile number.
Use this instead of :func:is_valid_phone_br whenever the number is
a delivery address -- WhatsApp, SMS, an OTP. A landline passes
:func:is_valid_phone_br and then fails silently at delivery time,
with no error for the user and no obvious log for the operator.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
str
|
The phone string to inspect. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
|
bool
|
9-digit subscriber number starting with |
is_valid_phone_br
¶
Check whether value looks like a Brazilian phone number.
Accepts optional +55 country code, optional DDD parentheses
and an optional 9th digit for mobile numbers. After stripping
non-digits the remaining length must be 10 (landline) or 11
(mobile), with an optional leading 55 country code.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
str
|
The phone string to inspect. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
|
is_valid_pix_key
¶
Return True when value is a valid PIX key of any type.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
str
|
The PIX key to check. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
Whether the value is a recognizable, valid PIX key. |
MobilePhoneBRField
module-attribute
¶
MobilePhoneBRField = Annotated[str, AfterValidator(normalize_mobile_phone_br)]
Pydantic field type that accepts only a BR mobile number.
Rejects landlines, which :data:PhoneBRField accepts, and normalizes to
the 11 digits of the national form (DDD + subscriber number) so the
same line always lands in the column as the same string.
normalize_cep
¶
Return value as 8 digits, validating along the way.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
str
|
The CEP string (masked or unmasked). |
required |
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The CEP stripped down to 8 digits. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
normalize_cnpj
¶
Return value as 14 digits, validating along the way.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
str
|
The CNPJ string (masked or unmasked). |
required |
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The CNPJ stripped down to 14 digits. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
normalize_cpf
¶
Return value as 11 digits, validating along the way.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
str
|
The CPF string (masked or unmasked). |
required |
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The CPF stripped down to 11 digits. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
normalize_cpf_cnpj
¶
Return value as 11 or 14 digits, validating along the way.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
str
|
The document string (masked or unmasked). |
required |
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The document stripped down to digits only. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
normalize_mobile_phone_br
¶
Return a BR mobile number as the 11 digits of its national form.
Unlike :func:normalize_phone_br, which keeps whatever the caller
typed and therefore returns 10, 11, 12 or 13 digits, this one always
returns DDD + 9-digit subscriber number: the +55 country
code is dropped, so two spellings of the same line normalize to the
same string and compare equal in a database column. Use
:attr:PhoneNumberBR.e164 when the +55 form is what you need.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
str
|
The phone string (masked or unmasked). |
required |
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The mobile number as 11 digits. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
normalize_phone_br
¶
Return value as digits-only with an optional 55 prefix.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
str
|
The phone string (masked or unmasked). |
required |
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The phone stripped down to digits only. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
normalize_pix_key
¶
Validate a PIX key and return it in canonical form.
Canonicalization per type: CPF/CNPJ → digits only; e-mail → trimmed +
lowercased; phone → the E.164 +55… string; random → lowercased
UUID.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
str
|
The raw PIX key. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The normalized key. |
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
only_digits
¶
Strip every non-digit character from value.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
str
|
The raw input (masked CPF, phone, etc.). |
required |
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
A string containing only the digits found in |
parse_phone_br
¶
parse_phone_br(value: str) -> PhoneNumberBR | None
Split a BR phone number into area code, subscriber number and kind.
Stricter than :func:is_valid_phone_br, which checks shape and
length only: this one also applies the ANATEL prefix rules, so an
8-digit subscriber number that does not start with 2-5
returns None even though :func:is_valid_phone_br accepts it.
A 9-digit subscriber number needs no prefix check here: the optional
9 in :data:PHONE_BR_PATTERN is the only way an 11-digit number
matches at all, so the leading 9 is already guaranteed by the
time this function runs. test_pattern_already_forces_the_ninth_digit
pins that coupling.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
str
|
The phone string, masked or unmasked, with or
without the |
required |
Returns:
| Type | Description |
|---|---|
PhoneNumberBR | None
|
PhoneNumberBR | None: The parsed number, or |
PhoneNumberBR | None
|
|
PHONE_BR_PATTERN
module-attribute
¶
PHONE_BR_PATTERN: Final[Pattern[str]] = re.compile(
"^(?:\\+?55\\s?)?(?:\\(?\\d{2}\\)?\\s?)?9?\\d{4}[-\\s]?\\d{4}$"
)
Match a BR phone number with optional +55, DDD, mask or 9th digit.
PhoneBRField
module-attribute
¶
PhoneBRField = Annotated[str, AfterValidator(normalize_phone_br)]
Pydantic field type that validates a BR phone and normalizes to digits.
PhoneNumberBR
¶
Bases: BaseModel
A Brazilian phone number split into its parts.
Returned by :func:parse_phone_br. The country code never shows up
in :attr:area_code or :attr:number, only in :attr:e164, so the
national parts compare equal whether or not the caller typed
+55.
Attributes:
| Name | Type | Description |
|---|---|---|
area_code |
str
|
The two-digit area code (DDD), e.g. |
number |
str
|
The subscriber number without the area code: 9 digits for a mobile line, 8 for a landline. |
is_mobile |
bool
|
Whether the line is a mobile one -- the question a WhatsApp/SMS delivery path actually asks. |
e164 |
str
|
The number in E.164 form, e.g. |
PixKeyField
module-attribute
¶
PixKeyField = Annotated[str, AfterValidator(normalize_pix_key)]
Pydantic field type that validates any PIX key and normalizes it.
Accepts a CPF, CNPJ, e-mail, E.164 phone (+55…) or random UUID key;
raises ValidationError (HTTP 422) on anything else. Use
:func:detect_pix_key_type when you also need to know which type.
PixKeyType
¶
Bases: BaseStrEnum
The five kinds of PIX key defined by BACEN.
CPF— an 11-digit CPF (individual taxpayer id).CNPJ— a 14-digit CNPJ (company taxpayer id).EMAIL— an e-mail address.PHONE— an E.164 phone (+55+ DDD + number).RANDOM— a random key (EVP), i.e. a UUID.
SupportsWebViewLink
¶
Bases: Protocol
An upload backend that can give a permanent link to a stored file.
The link is not a presigned URL: it does not expire and only opens for
someone the store itself authorizes (the Google Drive webViewLink
opens for a Drive user with access to the file). The admin download
route redirects to it when :meth:UploadStorage.presigned_url has
nothing to offer.
web_view_link
async
¶
Return the permanent link of the file under key.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
Storage key. |
required |
Returns:
| Type | Description |
|---|---|
str | None
|
str | None: The link, or |
UploadResult
dataclass
¶
Outcome of an :meth:UploadStorage.write_stream call.
The key is the canonical identifier for the persisted
object — a path string for the local backend, an S3 key for
MinIO. path is set only when the backend wrote to a real
filesystem location; url only when the backend can mint
a download URL (presigned or static).
Attributes:
| Name | Type | Description |
|---|---|---|
key |
str
|
Identifier used to read the object back. |
size |
int
|
Bytes written. |
path |
Path | None
|
On-disk path when applicable. |
url |
str | None
|
Public or presigned download URL when applicable. |
UploadStorage
¶
Bases: Protocol
Protocol every upload backend implements.
Implementations must be safe to call concurrently — FastAPI routes share the same instance.
write_stream
async
¶
write_stream(
key: str,
chunks: AsyncIterator[bytes],
*,
content_type: str = "application/octet-stream",
metadata: dict[str, str] | None = None,
max_size_bytes: int | None = None,
validator: ContentValidator | None = None,
) -> UploadResult
Persist a chunked async stream under key.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
Storage key. Backends interpret this as a relative path (local) or object key (S3). |
required |
chunks
|
AsyncIterator[bytes]
|
Source stream. |
required |
content_type
|
str
|
MIME type of the payload. |
'application/octet-stream'
|
metadata
|
dict[str, str] | None
|
User metadata. |
None
|
max_size_bytes
|
int | None
|
When set, the backend aborts the write and removes any partial object once the limit is exceeded. |
None
|
validator
|
ContentValidator | None
|
Optional callable invoked with the
first chunk. Returning |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
UploadResult |
UploadResult
|
Identifier + size + optional path/url. |
Raises:
| Type | Description |
|---|---|
FileTooLargeException
|
When |
InvalidFileTypeException
|
When |
delete
async
¶
Delete the object under key.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
Storage key. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
|
bool
|
when it was already gone. |
exists
async
¶
Return whether an object lives at key.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
Storage key. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
|
presigned_url
async
¶
Return a temporary download URL, or say the backend has none.
A backend says it cannot mint one in either of two ways: it
returns None (local disk), or it raises
:class:~tempest_fastapi_sdk.exceptions.PresignedUrlUnsupportedException
(Google Drive, which has no temporary link and refuses to pass a
permanent one off as such). A caller that works with any backend
handles both forms the same way.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
Storage key. |
required |
expires
|
timedelta
|
URL lifetime. |
timedelta(hours=1)
|
Returns:
| Type | Description |
|---|---|
str | None
|
str | None: Download URL. |
str | None
|
cannot mint one (e.g. local disk). |
Raises:
| Type | Description |
|---|---|
PresignedUrlUnsupportedException
|
From a backend that signals
"no presigned URLs" by raising instead of returning
|
login_throttle_key
¶
Return the per-identifier login throttle key for identifier.
"login:<sha256 of the stripped, lowercased identifier>" — hashed so
the throttle backend (often a shared Redis) never stores the address,
and normalized so Root@Example.com and root@example.com spend
one budget. Shared by POST /auth/login and POST /admin/login,
which is what keeps the two from drifting into two key shapes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
identifier
|
str
|
The submitted login identifier (an e-mail). |
required |
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The throttle key. |
ThrottleBackend
¶
Bases: Protocol
Minimal async key-value contract a throttle backend must satisfy.
Matches the relevant subset of redis.asyncio.Redis.
incr
¶
Atomically increment name and return the new value.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Identifier being throttled (an IP, a user, an email).
Positional-only: |
required |
Returns:
| Type | Description |
|---|---|
Awaitable[int]
|
Awaitable[int]: Resolves to the current attempt count. |
expire
¶
Set a TTL (seconds) on name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Identifier being throttled (an IP, a user, an email). |
required |
seconds
|
int
|
Window length in seconds. Positional-only
because |
required |
Returns:
| Type | Description |
|---|---|
Awaitable[object]
|
Awaitable[object]: Resolves once the backend call completes.
The result is discarded, so any return type is accepted —
|
ttl
¶
Return remaining TTL in seconds (-1/-2 when unset).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Identifier being throttled (an IP, a user, an email). |
required |
Returns:
| Type | Description |
|---|---|
Awaitable[int]
|
Awaitable[int]: Resolves to the remaining TTL in seconds. |
get
¶
Return the value at name (None when absent).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Identifier being throttled (an IP, a user, an email). |
required |
Returns:
| Type | Description |
|---|---|
Awaitable[str | bytes | None]
|
Awaitable[str | bytes | None]: Resolves to the stored counter
as text, or |
delete
¶
Delete name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Identifier being throttled (an IP, a user, an email).
Positional-only because |
required |
Returns:
| Type | Description |
|---|---|
Awaitable[object]
|
Awaitable[object]: Resolves once the backend call completes.
The result is discarded, so any return type is accepted —
|
ThrottleStatus
dataclass
¶
Outcome of a throttle query.
Attributes:
| Name | Type | Description |
|---|---|---|
attempts |
int
|
Failures recorded in the current window. |
blocked |
bool
|
Whether the attempt budget is exhausted. |
retry_after_seconds |
int
|
Seconds until the window resets.
|
ACCESS_TOKEN_TYPE
module-attribute
¶
typ of a token that authorizes API calls.
AMR_CLAIM
module-attribute
¶
Claim listing how the session was authenticated (RFC 8176, amr).
AMR_EMAIL_LINK
module-attribute
¶
amr value for a session opened by a single-use emailed link — account
activation or password reset. Not in the RFC 8176 registry, like
:data:AMR_EXTERNAL: the request proved control of the mailbox, not
knowledge of the password, and RFC 8176 has no value for that. Kept out of
:data:MFA_AMR_METHODS, so make_mfa_required_dependency refuses it, and
deliberately not otp: a link is one factor, and calling it a one-time
password would let it pass the second-factor gate.
AMR_EXTERNAL
module-attribute
¶
amr value for a session that an OAuth provider authenticated. Not in
the RFC 8176 registry: the SDK cannot see which methods the provider used,
so it records only that the proof happened elsewhere.
AMR_HARDWARE_KEY
module-attribute
¶
amr value for a WebAuthn assertion (RFC 8176: proof of possession of
a hardware-secured key).
AMR_OTP
module-attribute
¶
amr value for a one-time code — a TOTP code or a single-use
recovery code, both of which RFC 8176 files under "one-time password".
AMR_PASSWORD
module-attribute
¶
amr value for a password check (RFC 8176).
MFA_AMR
module-attribute
¶
MFA_AMR: tuple[str, ...] = (AMR_PASSWORD, AMR_OTP)
amr of a session that passed the password and the second factor.
MFA_AMR_METHODS
module-attribute
¶
MFA_AMR_METHODS: frozenset[str] = frozenset({AMR_OTP})
The amr values that prove a second factor by default.
MFA_TOKEN_TYPE
module-attribute
¶
typ of the token bridging step one and step two of an MFA login.
PASSWORD_AMR
module-attribute
¶
PASSWORD_AMR: tuple[str, ...] = (AMR_PASSWORD,)
amr of a session opened with the password alone.
REFRESH_TOKEN_TYPE
module-attribute
¶
typ of a token that only buys a new access/refresh pair.
STREAM_TOKEN_TYPE
module-attribute
¶
typ of a short-lived SSE ticket: it opens one event stream and
authorizes nothing else, so the URL it travels in can leak without
leaking a session. Minted by the POST <prefix>/ticket route of
:func:~tempest_fastapi_sdk.make_sse_router.