tempest_fastapi_sdk.storage¶
Object storage (MinIO, S3 ou disco local), upload resumível (tus) e os clientes de storage.
AsyncMinIOClient
¶
AsyncMinIOClient(
endpoint: str,
access_key: str,
secret_key: str,
*,
default_bucket: str = "uploads",
secure: bool = False,
region: str = "us-east-1",
session_token: str | None = None,
public_endpoint: str | None = None,
public_secure: bool | None = None,
accel_redirect: bool = False,
accel_prefix: str = "/_bucket/",
enabled: bool = True,
)
Async-friendly facade over minio.Minio.
Use as an async context manager when you want explicit cleanup,
or hold a long-lived instance on the FastAPI app — the
underlying Minio client is thread-safe and reuses its
connection pool.
Example:
>>> from tempest_fastapi_sdk import AsyncMinIOClient
>>> storage = AsyncMinIOClient(
... endpoint="localhost:9000",
... access_key="minioadmin",
... secret_key="minioadmin",
... default_bucket="uploads",
... )
>>> await storage.ensure_bucket()
>>> await storage.put_object("hello.txt", b"world")
>>> body = await storage.get_object_bytes("hello.txt")
>>> assert body == b"world"
Initialize the client.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
endpoint
|
str
|
|
required |
access_key
|
str
|
S3 access key. |
required |
secret_key
|
str
|
S3 secret key. |
required |
default_bucket
|
str
|
Bucket used by object operations
when no explicit |
'uploads'
|
secure
|
bool
|
Use HTTPS when |
False
|
region
|
str
|
S3 region. Match the bucket region for AWS S3; any value works for MinIO. |
'us-east-1'
|
session_token
|
str | None
|
Optional STS session token for temporary credentials. |
None
|
public_endpoint
|
str | None
|
Split-endpoint mode. When set,
presigned URLs (:meth: |
None
|
public_secure
|
bool | None
|
HTTPS for |
None
|
accel_redirect
|
bool
|
Delivery mode of :meth: |
False
|
accel_prefix
|
str
|
Internal nginx location the
|
'/_bucket/'
|
enabled
|
bool
|
|
True
|
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
ImportError
|
When the |
Notes
In split-endpoint mode a second client is built with the
same credentials, whose only job is signing presigned URLs
against the public host. SigV4 signs the Host header,
so the URL has to be signed with the public endpoint —
rewriting the host afterwards would invalidate the
signature.
client
property
¶
Return the underlying minio.Minio used for server-side calls.
Every operation of this class goes through it (or through
:attr:_presign_client), which is what makes a disabled client
refuse all of them at one point.
Returns:
| Name | Type | Description |
|---|---|---|
Minio |
Minio
|
The configured |
Raises:
| Type | Description |
|---|---|
IntegrationDisabledException
|
When the client was built with
|
bucket_exists
async
¶
Check whether bucket exists.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bucket
|
str | None
|
Target bucket; defaults to
|
None
|
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
|
bool
|
with the configured credentials. |
ensure_bucket
async
¶
Create the bucket if it does not exist yet.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bucket
|
str | None
|
Target bucket; defaults to
|
None
|
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
|
bool
|
when it already existed. |
list_buckets
async
¶
Return every bucket reachable with the current credentials.
Returns:
| Type | Description |
|---|---|
list[str]
|
list[str]: Bucket names. Empty list when none exist. |
remove_bucket
async
¶
Delete an empty bucket.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bucket
|
str | None
|
Target bucket; defaults to
|
None
|
Raises:
| Type | Description |
|---|---|
S3Error
|
When the bucket is missing or non-empty. |
put_object
async
¶
put_object(
key: str,
data: bytes | BinaryIO,
*,
bucket: str | None = None,
content_type: str = "application/octet-stream",
metadata: dict[str, str] | None = None,
length: int | None = None,
part_size: int = 10 * 1024 * 1024,
) -> str
Upload an object.
Accepts both raw bytes and any binary file-like object
(open("file", "rb"), BytesIO, UploadFile.file).
For unknown-length streams pass length=-1 to enable
multipart upload via part_size chunks.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
Destination object key. |
required |
data
|
bytes | BinaryIO
|
Payload. |
required |
bucket
|
str | None
|
Override target bucket. |
None
|
content_type
|
str
|
MIME type. |
'application/octet-stream'
|
metadata
|
dict[str, str] | None
|
User metadata. Keys
are stored under the |
None
|
length
|
int | None
|
Payload size in bytes. Required
for unknown-length streams; computed automatically
when |
None
|
part_size
|
int
|
Chunk size for multipart upload (when
|
10 * 1024 * 1024
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
ETag of the uploaded object (quotes stripped). |
Raises:
| Type | Description |
|---|---|
S3Error
|
When the upload fails (auth, network, bucket missing, content rejected). |
fput_object
async
¶
fput_object(
key: str,
file_path: str | Path,
*,
bucket: str | None = None,
content_type: str = "application/octet-stream",
metadata: dict[str, str] | None = None,
) -> str
Upload a file from disk.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
Destination object key. |
required |
file_path
|
str | Path
|
Source path on disk. |
required |
bucket
|
str | None
|
Override target bucket. |
None
|
content_type
|
str
|
MIME type. |
'application/octet-stream'
|
metadata
|
dict[str, str] | None
|
User metadata. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
ETag of the uploaded object (quotes stripped). |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
When |
S3Error
|
When the upload fails. |
get_object_bytes
async
¶
Download an object as bytes.
Suitable for small objects. For large payloads prefer
:meth:stream_object to avoid loading everything in memory.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
Object key. |
required |
bucket
|
str | None
|
Override source bucket. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
bytes |
bytes
|
Object payload. |
Raises:
| Type | Description |
|---|---|
S3Error
|
When the object is missing or the request fails. |
fget_object
async
¶
Download an object straight to disk.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
Object key. |
required |
file_path
|
str | Path
|
Destination path. Parent directories are created if missing. |
required |
bucket
|
str | None
|
Override source bucket. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
Path |
Path
|
The path the object was written to. |
Raises:
| Type | Description |
|---|---|
S3Error
|
When the object is missing or the request fails. |
stream_object
async
¶
stream_object(
key: str,
*,
bucket: str | None = None,
chunk_size: int = 64 * 1024,
offset: int = 0,
length: int | None = None,
) -> AsyncIterator[bytes]
Stream an object (or one byte range of it) in fixed-size chunks.
The whole network read still runs in a worker thread —
each chunk_size read is one asyncio.to_thread
round-trip — but the event loop yields between chunks so
other requests progress.
offset and length are forwarded to Minio.get_object,
which turns them into a Range header on the request to the
store, so only that slice crosses the network — what a 206
response needs. A whole-object read (the defaults) still calls
get_object(bucket, key) without them, so a test double written
against the older two-argument call keeps working.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
Object key. |
required |
bucket
|
str | None
|
Override source bucket. |
None
|
chunk_size
|
int
|
Bytes per chunk. Default 64 KiB. |
64 * 1024
|
offset
|
int
|
First byte to read. Default |
0
|
length
|
int | None
|
How many bytes to read from |
None
|
Returns:
| Type | Description |
|---|---|
AsyncIterator[bytes]
|
AsyncIterator[bytes]: Async generator yielding chunks |
AsyncIterator[bytes]
|
until the stream ends. |
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
S3Error
|
When the object is missing or the request fails. |
download_response
async
¶
download_response(
key: str,
*,
request: Request | None = None,
bucket: str | None = None,
filename: str | None = None,
media_type: str | None = None,
as_attachment: bool = True,
chunk_size: int = 64 * 1024,
cache_control: str | None = None,
headers: dict[str, str] | None = None,
) -> StreamingResponse
Stream an object straight to the client as a download response.
Reads the object's metadata (for the content type, length and
validators) and streams its bytes through the app — the file
never lands on the app's disk nor loads fully into memory. Reach for
this when the download must be auth-gated or the MinIO endpoint is
not publicly reachable; prefer :meth:presigned_get_url to offload
the transfer to MinIO directly when the client can hit it.
Every response carries Accept-Ranges: bytes plus the object's
ETag (quoted) and Last-Modified, and the download security
headers of
:data:~tempest_fastapi_sdk.api.static.DEFAULT_STATIC_SECURITY_HEADERS,
since the bytes reach the client on the API's origin with the type
stored at upload. Pass request to let the client use the
validators:
If-None-Matchmatching the ETag — or, when noIf-None-Matchis sent,If-Modified-Sincenot older than the object — answers304with no body, without reading the object.Range: bytes=a-b,bytes=a-orbytes=-nanswers206withContent-Range, reading only that slice from the store (offset/lengthonget_object). This is what lets a<video>seek and a download manager resume.- A range starting at or past the end answers
416withContent-Range: bytes */<size>. - Several ranges (
bytes=0-1,5-6), an unparseableRange, or anIf-Rangethat no longer matches the object serve the whole object with200— RFC 9110 allows ignoringRange, and it avoids amultipart/byterangesbody.
Without request no request header is read and the response is
always 200 with the whole object.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
Object key. |
required |
request
|
Request | None
|
The incoming request, whose |
None
|
bucket
|
str | None
|
Override source bucket. |
None
|
filename
|
str | None
|
Name presented to the client. Defaults to the object key's basename. |
None
|
media_type
|
str | None
|
Content type. Defaults to the object's
stored content type, then a guess from |
None
|
as_attachment
|
bool
|
|
True
|
chunk_size
|
int
|
Bytes per streamed chunk. Default 64 KiB. |
64 * 1024
|
cache_control
|
str | None
|
|
None
|
headers
|
dict[str, str] | None
|
Extra response headers. One named like a security default replaces that default. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
StreamingResponse |
StreamingResponse
|
Response ready to return from a router — |
StreamingResponse
|
|
|
StreamingResponse
|
body. |
Raises:
| Type | Description |
|---|---|
S3Error
|
When the object is missing or the request fails. |
accel_redirect_response
async
¶
accel_redirect_response(
key: str,
*,
bucket: str | None = None,
internal_prefix: str | None = None,
expires: timedelta = timedelta(minutes=5),
filename: str | None = None,
media_type: str | None = None,
as_attachment: bool = True,
cache_control: str | None = None,
headers: dict[str, str] | None = None,
) -> Response
Hand the transfer to nginx with an X-Accel-Redirect header.
The route keeps the authorisation decision and nginx moves the
bytes: the response is empty and carries
X-Accel-Redirect: <internal_prefix><bucket>/<key>?X-Amz-..., a
URL presigned against the internal endpoint — never
public_endpoint — so the bucket stays private and the client
only ever sees the backend's domain. nginx follows the header into
an internal location that proxies to the bucket; the client's
Range and If-None-Match travel with that request, so 206
and 304 come from the store itself.
SigV4 signs the Host header and the path, so the internal
location must strip the prefix (proxy_pass with a trailing
/) and send Host equal to endpoint; otherwise the store
answers 403 SignatureDoesNotMatch. The storage recipe carries
the full nginx block.
Content-Disposition, Content-Type and Cache-Control are
not set on this response but signed into the URL as the S3
response-* overrides, so the store returns them with the bytes.
Measured on nginx 1.27.5: the upstream's Content-Type wins over
the one the app sets, and a Content-Disposition set on both
reaches the client twice.
The download security headers
(:data:~tempest_fastapi_sdk.api.static.DEFAULT_STATIC_SECURITY_HEADERS)
are not set here: S3 has no response-* override for them, and
nginx answers with the store's response — measured on nginx 1.22.1,
1.27.5 and 1.29.8, a Content-Security-Policy the app sets on the
empty response does not reach the client. They belong in the
internal location, as add_header ... always; the storage
recipe's nginx block carries them.
No stat is made: a missing object surfaces as the store's
404 through nginx instead of an S3Error here.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
Object key. |
required |
bucket
|
str | None
|
Override source bucket. |
None
|
internal_prefix
|
str | None
|
The nginx |
None
|
expires
|
timedelta
|
Lifetime of the presigned URL. nginx uses it at once, so it only has to outlive the hop. Default five minutes. |
timedelta(minutes=5)
|
filename
|
str | None
|
Name presented to the client. Defaults to the object key's basename. |
None
|
media_type
|
str | None
|
Content type the store should answer
with, a bare |
None
|
as_attachment
|
bool
|
|
True
|
cache_control
|
str | None
|
|
None
|
headers
|
dict[str, str] | None
|
Extra headers on the app's response. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
Response |
Response
|
An empty |
Response
|
nginx to replace with the object. |
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
serve_object
async
¶
serve_object(
key: str,
*,
request: Request | None = None,
bucket: str | None = None,
filename: str | None = None,
media_type: str | None = None,
as_attachment: bool = True,
cache_control: str | None = None,
headers: dict[str, str] | None = None,
) -> Response
Serve an object the way the constructor's accel_redirect says.
One route, two delivery modes chosen by configuration
(STORAGE_ACCEL_REDIRECT via :meth:MinIOSettings.minio_kwargs):
accel_redirect=False proxies the bytes through the app with
:meth:download_response; True answers with
:meth:accel_redirect_response into accel_prefix. Both honour
Range and revalidation — the first in the app, the second in the
store behind nginx.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
Object key. |
required |
request
|
Request | None
|
The incoming request. Proxy mode needs
it for |
None
|
bucket
|
str | None
|
Override source bucket. |
None
|
filename
|
str | None
|
Name presented to the client. Defaults to the object key's basename. |
None
|
media_type
|
str | None
|
Content type. |
None
|
as_attachment
|
bool
|
|
True
|
cache_control
|
str | None
|
|
None
|
headers
|
dict[str, str] | None
|
Extra headers on the app's response. In proxy mode, one named like a security default replaces that default. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
Response |
Response
|
A :class: |
Response
|
|
Raises:
| Type | Description |
|---|---|
S3Error
|
Proxy mode, when the object is missing or the request fails. |
stat_object
async
¶
stat_object(key: str, *, bucket: str | None = None) -> ObjectStat
Fetch metadata for an object without downloading it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
Object key. |
required |
bucket
|
str | None
|
Override source bucket. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
ObjectStat |
ObjectStat
|
Subset of fields commonly needed by callers. |
ObjectStat
|
Use |
|
ObjectStat
|
on this client). |
Raises:
| Type | Description |
|---|---|
S3Error
|
When the object is missing. |
list_objects
async
¶
List object keys under a prefix.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prefix
|
str
|
Prefix filter. Empty string returns everything. |
''
|
bucket
|
str | None
|
Override source bucket. |
None
|
recursive
|
bool
|
Walk into pseudo-directories.
|
True
|
Returns:
| Type | Description |
|---|---|
list[str]
|
list[str]: Object keys. Empty list when no matches — |
list[str]
|
matching the SDK convention of "no rows is not an |
list[str]
|
error". |
remove_object
async
¶
Delete an object (or a specific version).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
Object key. |
required |
bucket
|
str | None
|
Override target bucket. |
None
|
version_id
|
str | None
|
When the bucket has versioning enabled, the specific version to delete. |
None
|
Raises:
| Type | Description |
|---|---|
S3Error
|
When the delete fails for a reason other than "already gone" (deletes are idempotent on S3). |
remove_objects
async
¶
remove_objects(
keys: Iterable[str], *, bucket: str | None = None
) -> list[ObjectDeleteError]
Delete many objects with S3 batch deletes.
Uses Minio.remove_objects, which sends one DeleteObjects
request per 1000 keys instead of one DELETE per key. Duplicate
keys are collapsed. Keys that do not exist count as deleted (S3
deletes are idempotent), so they never appear in the result.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
keys
|
Iterable[str]
|
Object keys to delete. |
required |
bucket
|
str | None
|
Override target bucket. |
None
|
Returns:
| Type | Description |
|---|---|
list[ObjectDeleteError]
|
list[ObjectDeleteError]: The keys the store refused to delete, |
list[ObjectDeleteError]
|
with the reported error. Empty list when every key was deleted. |
Raises:
| Type | Description |
|---|---|
S3Error
|
When a whole batch request fails (auth, network, bucket missing). |
copy_object
async
¶
copy_object(
source_key: str,
dest_key: str,
*,
source_bucket: str | None = None,
dest_bucket: str | None = None,
) -> str
Copy an object inside the same store.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source_key
|
str
|
Source object key. |
required |
dest_key
|
str
|
Destination object key. |
required |
source_bucket
|
str | None
|
Source bucket; defaults to
|
None
|
dest_bucket
|
str | None
|
Destination bucket; defaults
to |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
ETag of the copied object (quotes stripped). |
Raises:
| Type | Description |
|---|---|
S3Error
|
When the source is missing or the copy fails. |
presigned_get_url
async
¶
presigned_get_url(
key: str,
*,
bucket: str | None = None,
expires: timedelta = timedelta(hours=1),
filename: str | None = None,
media_type: str | None = None,
as_attachment: bool | None = None,
) -> str
Generate a temporary download URL.
With filename, media_type or as_attachment the headers
the store answers with are signed into the URL as S3 response-*
overrides, the same ones :meth:download_response signs — so the
link serves the type the server checked, not the one the uploader
declared. Changing them in the URL breaks the signature. With none
of them the store answers with what it stored.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
Object key. |
required |
bucket
|
str | None
|
Override source bucket. |
None
|
expires
|
timedelta
|
URL lifetime. Maximum is 7 days (S3 hard limit). |
timedelta(hours=1)
|
filename
|
str | None
|
Name presented to the client; signs a
|
None
|
media_type
|
str | None
|
|
None
|
as_attachment
|
bool | None
|
|
None
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
Pre-signed HTTPS URL that anyone with the link |
str
|
can |
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
presigned_put_url
async
¶
presigned_put_url(
key: str, *, bucket: str | None = None, expires: timedelta = timedelta(minutes=15)
) -> str
Generate a temporary upload URL.
Lets the browser PUT directly to MinIO/S3 without the
bytes touching the FastAPI process — ideal for large
files.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
Destination object key. |
required |
bucket
|
str | None
|
Override target bucket. |
None
|
expires
|
timedelta
|
URL lifetime. Maximum is 7 days. |
timedelta(minutes=15)
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
Pre-signed HTTPS URL accepting a |
str
|
object body until expiry. |
presigned_post_policy
async
¶
presigned_post_policy(
key: str,
*,
max_bytes: int,
content_type: str | None = None,
min_bytes: int = 0,
bucket: str | None = None,
expires: timedelta = timedelta(minutes=15),
) -> PresignedPost
Generate a form upload the store caps at max_bytes.
A presigned PUT signs nothing about the body, so the service
only learns the size after the bytes landed. An S3 POST policy
carries a content-length-range condition, and the store refuses
the upload itself (400 EntityTooLarge / EntityTooSmall) —
the same cap the local backend's route applies. The key, and the
Content-Type when given, are eq conditions too: the form
cannot be reused for another object or another type.
The URL is path-style (<scheme>://<host>/<bucket>) on the
signing host — public_endpoint when set.
Signing is local: with region set (it always is here) the
client never asks the store for the bucket's region, so it runs in
the event loop. minio 7.2.20 calls datetime.utcnow() while
signing; that DeprecationWarning is silenced around the call,
because a service running filterwarnings = ["error"] would
otherwise fail every upload it tries to sign.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
Destination object key. |
required |
max_bytes
|
int
|
Largest accepted file, in bytes. |
required |
content_type
|
str | None
|
The only |
None
|
min_bytes
|
int
|
Smallest accepted file. Default |
0
|
bucket
|
str | None
|
Override target bucket. |
None
|
expires
|
timedelta
|
Policy lifetime. Maximum is 7 days. |
timedelta(minutes=15)
|
Returns:
| Name | Type | Description |
|---|---|---|
PresignedPost |
PresignedPost
|
The URL, the form fields to send before the file, |
PresignedPost
|
and the cap. |
Raises:
| Type | Description |
|---|---|
ValueError
|
When the size range is empty or inverted, or
|
IntegrationDisabledException
|
When the client was built with
|
presigned_get_urls
async
¶
presigned_get_urls(
keys: Iterable[str],
*,
bucket: str | None = None,
expires: timedelta = timedelta(hours=1),
max_concurrency: int = 16,
) -> dict[str, str]
Generate presigned download URLs for many keys concurrently.
Duplicate keys are collapsed, so each object is signed once and appears a single time in the result. Signing is fail-fast: the first failure aborts the batch and propagates.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
keys
|
Iterable[str]
|
Object keys to sign. |
required |
bucket
|
str | None
|
Override source bucket for every key. |
None
|
expires
|
timedelta
|
URL lifetime for every key. Maximum is 7 days (S3 hard limit). |
timedelta(hours=1)
|
max_concurrency
|
int
|
Maximum signings awaited at once. |
16
|
Returns:
| Type | Description |
|---|---|
dict[str, str]
|
dict[str, str]: Mapping of each unique key to its presigned |
dict[str, str]
|
GET URL. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
S3Error
|
When signing a key fails. |
put_objects
async
¶
put_objects(
items: Iterable[PutObjectItem],
*,
bucket: str | None = None,
max_concurrency: int = 16,
) -> dict[str, str]
Upload many objects concurrently.
Uploads are fail-fast: the first failure aborts the batch and propagates. When two items share a key the later one wins in the returned mapping, matching last-write-wins on the store.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
items
|
Iterable[PutObjectItem]
|
The objects to upload, each carrying its key, payload and per-object options. |
required |
bucket
|
str | None
|
Override target bucket for every item. |
None
|
max_concurrency
|
int
|
Maximum uploads awaited at once. |
16
|
Returns:
| Type | Description |
|---|---|
dict[str, str]
|
dict[str, str]: Mapping of each item's key to the uploaded |
dict[str, str]
|
object's ETag (quotes stripped). |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
S3Error
|
When an upload fails. |
get_objects_bytes
async
¶
get_objects_bytes(
keys: Iterable[str], *, bucket: str | None = None, max_concurrency: int = 16
) -> dict[str, bytes]
Download many objects as bytes concurrently.
Duplicate keys are collapsed, so each object is fetched once.
Downloads are fail-fast: the first failure aborts the batch and
propagates. Suitable for small objects — stream large payloads
individually via :meth:stream_object.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
keys
|
Iterable[str]
|
Object keys to download. |
required |
bucket
|
str | None
|
Override source bucket for every key. |
None
|
max_concurrency
|
int
|
Maximum downloads awaited at once. |
16
|
Returns:
| Type | Description |
|---|---|
dict[str, bytes]
|
dict[str, bytes]: Mapping of each unique key to its payload. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
S3Error
|
When a download fails. |
ObjectStat
dataclass
¶
ObjectStat(
bucket: str,
key: str,
size: int,
etag: str | None,
content_type: str | None,
last_modified: datetime | None,
metadata: dict[str, str],
raw: Object | None,
)
Subset of object metadata returned by :meth:AsyncMinIOClient.stat_object.
The full minio.datatypes.Object instance is also reachable via
the raw attribute when you need the long tail of fields
(version id, owner, restoration state, etc.).
Attributes:
| Name | Type | Description |
|---|---|---|
bucket |
str
|
Bucket the object lives in. |
key |
str
|
Object key (S3 path). |
size |
int
|
Size in bytes. |
etag |
str | None
|
Server-side ETag (quotes stripped). |
content_type |
str | None
|
MIME type recorded at upload. |
last_modified |
datetime | None
|
Last modification timestamp in UTC. |
metadata |
dict[str, str]
|
User metadata keyed without the
|
raw |
Object | None
|
Underlying |
ObjectDeleteError
dataclass
¶
One key that :meth:AsyncMinIOClient.remove_objects failed to delete.
Attributes:
| Name | Type | Description |
|---|---|---|
key |
str
|
Object key the store refused to delete. |
code |
str
|
S3 error code reported for the key ( |
message |
str
|
Human-readable message reported by the store. |
BucketRoutedMinIOClient
¶
BucketRoutedMinIOClient(
endpoint: str,
access_key: str,
secret_key: str,
*,
bucket_credentials: Mapping[str, StorageBucketCredential],
default_bucket: str = "uploads",
secure: bool = False,
region: str = "us-east-1",
session_token: str | None = None,
public_endpoint: str | None = None,
public_secure: bool | None = None,
accel_redirect: bool = False,
accel_prefix: str = "/_bucket/",
enabled: bool = True,
)
Bases: AsyncMinIOClient
An :class:AsyncMinIOClient that signs each bucket with its own key.
Built like :class:AsyncMinIOClient, plus bucket_credentials. The
constructor arguments describe the primary credential, which answers
every bucket missing from bucket_credentials; each listed bucket
gets a client of its own with the same endpoint, region, TLS and public
endpoint, and only its keys swapped.
Every operation that takes bucket resolves it first
(bucket or default_bucket) and is sent through the client of that
bucket — presigned URLs included, so a link is signed by the key that
can read the object. Two calls name no bucket and stay on the primary
credential: :meth:list_buckets and the :attr:client property.
:meth:copy_object is the one call with two buckets. When both resolve
to the same credential it is the store's server-side copy, unchanged;
when they resolve to different credentials no single key can read the
source and write the destination, so the object is read with the source
key into a temporary file and uploaded with the destination key.
Example:
>>> from pydantic import SecretStr
>>> from tempest_fastapi_sdk.storage import (
... BucketRoutedMinIOClient,
... StorageBucketCredential,
... )
>>> storage = BucketRoutedMinIOClient(
... "storage.example.com",
... "images-key",
... "images-secret",
... default_bucket="images",
... secure=True,
... bucket_credentials={
... "documents": StorageBucketCredential(
... access_key="documents-key",
... secret_key=SecretStr("documents-secret"),
... ),
... },
... )
>>> sorted(storage.routed_buckets)
['documents']
Initialize the primary client and one client per listed bucket.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
endpoint
|
str
|
|
required |
access_key
|
str
|
Primary access key, used for every bucket
missing from |
required |
secret_key
|
str
|
Primary secret key. |
required |
bucket_credentials
|
Mapping[str, StorageBucketCredential]
|
Bucket name to the credential that reaches it. |
required |
default_bucket
|
str
|
Bucket of a call that names none. It is
routed like any other: listed in |
'uploads'
|
secure
|
bool
|
Use HTTPS when |
False
|
region
|
str
|
S3 region. |
'us-east-1'
|
session_token
|
str | None
|
STS session token of the primary credential only; the per-bucket clients sign without one. |
None
|
public_endpoint
|
str | None
|
Split-endpoint host presigned URLs are signed against, for every credential. |
None
|
public_secure
|
bool | None
|
HTTPS for |
None
|
accel_redirect
|
bool
|
Delivery mode of :meth: |
False
|
accel_prefix
|
str
|
Internal nginx location of
|
'/_bucket/'
|
enabled
|
bool
|
|
True
|
Raises:
| Type | Description |
|---|---|
ValueError
|
When a bucket name in |
ImportError
|
When the |
routed_buckets
property
¶
Return the buckets that have a credential of their own.
Empty when the client was built with enabled=False.
Returns:
| Type | Description |
|---|---|
frozenset[str]
|
frozenset[str]: Bucket names; any other bucket uses the |
frozenset[str]
|
primary credential. |
copy_object
async
¶
copy_object(
source_key: str,
dest_key: str,
*,
source_bucket: str | None = None,
dest_bucket: str | None = None,
) -> str
Copy an object, across credentials when the buckets need it.
Both buckets on the same credential: the store's server-side copy
(:meth:AsyncMinIOClient.copy_object). On different credentials:
the source is downloaded with its key into a temporary file
(deleted afterwards) and uploaded with the destination key, carrying
the source's Content-Type and user metadata. Other stored
headers (Cache-Control, Content-Disposition) are not carried
over on that path, and the bytes cross the app.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source_key
|
str
|
Source object key. |
required |
dest_key
|
str
|
Destination object key. |
required |
source_bucket
|
str | None
|
Source bucket; defaults to
|
None
|
dest_bucket
|
str | None
|
Destination bucket; defaults to
|
None
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
ETag of the copied object (quotes stripped). |
Raises:
| Type | Description |
|---|---|
S3Error
|
When the source is missing or either side refuses. |
IntegrationDisabledException
|
When the client was built with
|
LocalObjectStorageClient
¶
LocalObjectStorageClient(
base_dir: Path | str,
*,
public_url: str,
signing_secret: str,
default_bucket: str = "uploads",
route_prefix: str = DEFAULT_LOCAL_STORAGE_ROUTE_PREFIX,
max_upload_bytes: int = DEFAULT_LOCAL_MAX_UPLOAD_BYTES,
enabled: bool = True,
encryption_keys: Mapping[str, bytes] | None = None,
allow_plaintext_read: bool = False,
)
Object storage in a local directory, with signed links to the app.
Satisfies :class:~tempest_fastapi_sdk.privacy.SubjectStorageClient, so
it drops in where :class:~tempest_fastapi_sdk.storage.AsyncMinIOClient
goes under :class:~tempest_fastapi_sdk.privacy.SubjectObjectStorage.
Example:
>>> client = LocalObjectStorageClient(
... "/var/lib/app/storage",
... public_url="https://api.example.com",
... signing_secret=settings.JWT_SECRET,
... )
>>> await client.put_object("a.txt", b"hi", content_type="text/plain")
'49f68a5c8493ec2c0bf489821c21fc3b'
>>> await client.presigned_get_url("a.txt")
'https://api.example.com/storage/uploads/a.txt?expires=...&signature=...'
Attributes:
| Name | Type | Description |
|---|---|---|
base_dir |
Path
|
Resolved root of the store. |
public_url |
str
|
Scheme and host the links start with, no trailing slash. |
route_prefix |
str
|
Path the signed routes live under. |
default_bucket |
str
|
Bucket used when a call passes none. |
max_upload_bytes |
int
|
Largest body the signed |
enabled |
bool
|
|
allow_plaintext_read |
bool
|
Whether an object without the encrypted header is served as plaintext while encryption is on. |
Create the store's directories and keep the signing material.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
base_dir
|
Path | str
|
Root directory of the store. Created with its parents when missing. |
required |
public_url
|
str
|
Scheme and host the browser reaches the app
at ( |
required |
signing_secret
|
str
|
Secret the links are signed with. Domain
separation makes reusing |
required |
default_bucket
|
str
|
Bucket used when a call passes none.
Default |
'uploads'
|
route_prefix
|
str
|
Path the signed routes are mounted at, as the
app sees it in |
DEFAULT_LOCAL_STORAGE_ROUTE_PREFIX
|
max_upload_bytes
|
int
|
Largest body the signed |
DEFAULT_LOCAL_MAX_UPLOAD_BYTES
|
enabled
|
bool
|
|
True
|
encryption_keys
|
Mapping[str, bytes] | None
|
Key id to 32-byte
AES-256 key. Set, every object written is encrypted at rest
with the first key (insertion order), and an object is
read with whichever key its header names — put a new key
first to rotate, and keep the old ones until
:meth: |
None
|
allow_plaintext_read
|
bool
|
With |
False
|
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
ImportError
|
When |
encrypted
property
¶
Whether objects are written encrypted at rest.
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
|
write_key_id
property
¶
Id of the key new objects are sealed with.
Returns:
| Type | Description |
|---|---|
str | None
|
str | None: The first id of |
str | None
|
without encryption. |
check_key
staticmethod
¶
Validate an object key.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
The candidate key, |
required |
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
When the key is empty, starts with |
object_path
¶
Return where the bytes of key live on disk.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
Object key. |
required |
bucket
|
str | None
|
Bucket; |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
Path |
Path
|
The file path (it may not exist). |
Raises:
| Type | Description |
|---|---|
ValueError
|
When the bucket or key is invalid, or resolves out of the store. |
put_object
async
¶
put_object(
key: str,
data: bytes | BinaryIO,
*,
bucket: str | None = None,
content_type: str = "application/octet-stream",
metadata: dict[str, str] | None = None,
length: int | None = None,
) -> str
Store one object, replacing any previous one atomically.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
Object key. |
required |
data
|
bytes | BinaryIO
|
The payload; a stream is read up to
|
required |
bucket
|
str | None
|
Target bucket. |
None
|
content_type
|
str
|
MIME type, reported back by
:meth: |
'application/octet-stream'
|
metadata
|
dict[str, str] | None
|
User metadata, reported back by
:meth: |
None
|
length
|
int | None
|
Bytes to read from a stream; |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The ETag — the MD5 of the payload, hex; with |
str
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
When the bucket or key is invalid. |
OSError
|
When the write fails (disk full, permissions, a key that needs a directory where a file is). |
IntegrationDisabledException
|
When built with |
write_stream
async
¶
write_stream(
key: str,
chunks: AsyncIterator[bytes],
*,
bucket: str | None = None,
content_type: str = "application/octet-stream",
metadata: dict[str, str] | None = None,
max_bytes: int | None = None,
) -> str
Store an object from an async chunk stream, capped at max_bytes.
The stream is written to a temporary file as it arrives and moved into place only when it ended within the cap; going past the cap stops reading and leaves nothing behind.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
Object key. |
required |
chunks
|
AsyncIterator[bytes]
|
The payload, in order. |
required |
bucket
|
str | None
|
Target bucket. |
None
|
content_type
|
str
|
MIME type. |
'application/octet-stream'
|
metadata
|
dict[str, str] | None
|
User metadata. |
None
|
max_bytes
|
int | None
|
Largest payload accepted; |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The ETag — the MD5 of the payload, hex; with |
str
|
|
|
str
|
|
|
str
|
tags encryption adds. |
Raises:
| Type | Description |
|---|---|
FileTooLargeException
|
When the stream passes |
ValueError
|
When the bucket or key is invalid. |
OSError
|
When the write fails. |
IntegrationDisabledException
|
When built with |
presigned_get_url
async
¶
presigned_get_url(
key: str,
*,
bucket: str | None = None,
expires: timedelta = timedelta(hours=1),
filename: str | None = None,
media_type: str | None = None,
as_attachment: bool | None = None,
) -> str
Build a temporary download link served by the app.
The object does not need to exist yet; the route answers 404
if it still does not when the link is opened.
filename, media_type and as_attachment travel in the
query and are bound into the signature (:func:bound_purpose), the
way S3 signs its response-* overrides: the route answers with
them, and editing one breaks the link. Unset, the route serves the
stored type with its own as_attachment default.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
Object key. |
required |
bucket
|
str | None
|
Source bucket. |
None
|
expires
|
timedelta
|
Link lifetime; at most 7 days. |
timedelta(hours=1)
|
filename
|
str | None
|
Name presented to the client. |
None
|
media_type
|
str | None
|
|
None
|
as_attachment
|
bool | None
|
|
None
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
|
str
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
When the key is invalid or |
IntegrationDisabledException
|
When built with |
presigned_put_url
async
¶
presigned_put_url(
key: str, *, bucket: str | None = None, expires: timedelta = timedelta(minutes=15)
) -> str
Build a temporary upload link served by the app.
The client PUTs the raw bytes to it with a Content-Type
header; the route caps the body at :attr:max_upload_bytes. As with
S3, nothing about the payload is signed — verify it with
:meth:stat_object before trusting it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
Destination object key. |
required |
bucket
|
str | None
|
Target bucket. |
None
|
expires
|
timedelta
|
Link lifetime; at most 7 days. |
timedelta(minutes=15)
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The signed URL accepting a |
Raises:
| Type | Description |
|---|---|
ValueError
|
When the key is invalid or |
IntegrationDisabledException
|
When built with |
presigned_post_policy
async
¶
presigned_post_policy(
key: str,
*,
max_bytes: int,
content_type: str | None = None,
min_bytes: int = 0,
bucket: str | None = None,
expires: timedelta = timedelta(minutes=15),
) -> PresignedPost
Build a form upload the route caps at max_bytes.
The same call, and the same :class:PresignedPost, as
:meth:AsyncMinIOClient.presigned_post_policy
<tempest_fastapi_sdk.storage.AsyncMinIOClient.presigned_post_policy>:
the browser posts multipart/form-data with the fields and then
the file, and the code that sends it does not know which backend
signed. The limits ride in the URL, bound into the signature; the
route refuses a file outside them (413 FILE_TOO_LARGE /
400 FILE_TOO_SMALL), a different Content-Type field or a
different key field (403), and stores nothing.
Reading the form needs python-multipart (the [upload]
extra); it is checked here, so a missing extra fails where the link
is issued instead of on the uploader's request.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
Destination object key. |
required |
max_bytes
|
int
|
Largest accepted file; at most
:attr: |
required |
content_type
|
str | None
|
The only |
None
|
min_bytes
|
int
|
Smallest accepted file. Default |
0
|
bucket
|
str | None
|
Target bucket. |
None
|
expires
|
timedelta
|
Link lifetime; at most 7 days. |
timedelta(minutes=15)
|
Returns:
| Name | Type | Description |
|---|---|---|
PresignedPost |
PresignedPost
|
The URL, the form fields and the cap. |
Raises:
| Type | Description |
|---|---|
ValueError
|
When the size range is empty, inverted or above
:attr: |
ImportError
|
When |
IntegrationDisabledException
|
When built with |
verify_link
¶
Verify a link whose extra query parameters are bound to it.
The check behind the routes of
:func:~tempest_fastapi_sdk.storage.make_local_storage_router: the
purpose is rebuilt with :func:bound_purpose from the parameters in
names that the request carries, so a link whose
limits or overrides were edited verifies as another purpose and
fails.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
request
|
Request
|
The incoming request. |
required |
purpose
|
str
|
The route's base purpose. |
required |
names
|
tuple[str, ...]
|
The parameters this route binds —
:data: |
()
|
Returns:
| Type | Description |
|---|---|
dict[str, str]
|
dict[str, str]: The bound parameters the link carried. |
Raises:
| Type | Description |
|---|---|
InvalidSignedURLException
|
|
ExpiredSignedURLException
|
|
signature_dependency
¶
Build the FastAPI dependency that verifies this store's links.
:func:~tempest_fastapi_sdk.storage.make_local_storage_router uses
it; call it yourself only to serve the links from a route of your
own.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
purpose
|
str
|
:data: |
required |
Returns:
| Type | Description |
|---|---|
Callable[..., Coroutine[Any, Any, None]]
|
Callable[..., Coroutine[Any, Any, None]]: The dependency from |
Callable[..., Coroutine[Any, Any, None]]
|
func: |
Callable[..., Coroutine[Any, Any, None]]
|
bound to this store's secret. |
Raises:
| Type | Description |
|---|---|
ValueError
|
When the store was built with an empty secret. |
stat_object
async
¶
stat_object(key: str, *, bucket: str | None = None) -> ObjectStat
Describe a stored object without reading it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
Object key. |
required |
bucket
|
str | None
|
Source bucket. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
ObjectStat |
ObjectStat
|
Size and modification time from the file; content |
ObjectStat
|
type, metadata and ETag from the metadata file. |
|
ObjectStat
|
|
|
ObjectStat
|
|
|
ObjectStat
|
from the file's header and length without decrypting; a |
|
ObjectStat
|
plaintext file reports its own size. |
Raises:
| Type | Description |
|---|---|
LocalObjectNotFoundError
|
When the object is not stored. |
StorageIntegrityException
|
|
ValueError
|
When the bucket or key is invalid. |
IntegrationDisabledException
|
When built with |
stream_object
async
¶
stream_object(
key: str,
*,
bucket: str | None = None,
chunk_size: int = LOCAL_STORAGE_CHUNK_SIZE,
offset: int = 0,
length: int | None = None,
) -> AsyncIterator[bytes]
Open a stored object, or one byte range of it, as a chunk stream.
The file is opened before this returns, so a missing object fails
here and not at the first chunk. A length past the end yields
what exists.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
Object key. |
required |
bucket
|
str | None
|
Source bucket. |
None
|
chunk_size
|
int
|
Bytes per chunk. Default 64 KiB. |
LOCAL_STORAGE_CHUNK_SIZE
|
offset
|
int
|
First byte to read. |
0
|
length
|
int | None
|
Bytes to read from |
None
|
With encryption_keys, offset and length count plaintext
bytes, and only the blocks that overlap the range are read and
decrypted — a Range request or a capped
:meth:~tempest_fastapi_sdk.privacy.SubjectObjectStorage.read
decrypts no more than it serves. The first block is authenticated
before this returns; every later one before it is yielded.
Returns:
| Type | Description |
|---|---|
AsyncIterator[bytes]
|
AsyncIterator[bytes]: The chunks, in order; the file closes when |
AsyncIterator[bytes]
|
the stream ends or is closed. |
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
LocalObjectNotFoundError
|
When the object is not stored. |
StorageIntegrityException
|
With |
IntegrationDisabledException
|
When built with |
list_objects
async
¶
List object keys under prefix, sorted.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prefix
|
str
|
Prefix filter. |
''
|
bucket
|
str | None
|
Source bucket. |
None
|
recursive
|
bool
|
|
True
|
Returns:
| Type | Description |
|---|---|
list[str]
|
list[str]: The matching keys; |
list[str]
|
bucket. |
Raises:
| Type | Description |
|---|---|
ValueError
|
When the bucket is invalid. |
IntegrationDisabledException
|
When built with |
remove_object
async
¶
Delete one object; a missing key is not an error, as on S3.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
Object key. |
required |
bucket
|
str | None
|
Target bucket. |
None
|
version_id
|
str | None
|
Accepted for signature parity; a disk keeps no versions. |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
When the bucket or key is invalid. |
OSError
|
When the file cannot be removed (permissions). |
IntegrationDisabledException
|
When built with |
remove_objects
async
¶
remove_objects(
keys: Iterable[str], *, bucket: str | None = None
) -> list[ObjectDeleteError]
Delete many objects, reporting the ones that could not go.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
keys
|
Iterable[str]
|
Object keys; duplicates collapse. |
required |
bucket
|
str | None
|
Target bucket. |
None
|
Returns:
| Type | Description |
|---|---|
list[ObjectDeleteError]
|
list[ObjectDeleteError]: |
list[ObjectDeleteError]
|
|
list[ObjectDeleteError]
|
included); those objects stay. Empty when all were deleted. |
Raises:
| Type | Description |
|---|---|
IntegrationDisabledException
|
When built with |
encrypt_existing
async
¶
Encrypt every plaintext object under prefix with the write key.
The migration of a store that held files before encryption_keys
was set. Idempotent: an object that already has the encrypted header
is skipped, so running it twice — or after an interrupted run —
rewrites nothing that is done. Content type and metadata are kept;
the ETag becomes the MD5 of the encrypted file. Runs whether
allow_plaintext_read is on or off.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prefix
|
str
|
Only keys starting with it. Default: all. |
''
|
bucket
|
str | None
|
Bucket; |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
Objects encrypted by this call. |
Raises:
| Type | Description |
|---|---|
ValueError
|
When the client has no |
OSError
|
When a file cannot be read or written. |
IntegrationDisabledException
|
When built with |
reencrypt
async
¶
Rewrite every object sealed with an older key under the write key.
The second half of a key rotation: put the new key first in
encryption_keys (writes switch to it at once, reads keep working
with the old one), run this, then drop the old key. Idempotent: an
object already under the write key is skipped, and so is a plaintext
one (:meth:encrypt_existing handles those). An object that fails to
decrypt stops the run with the error, before anything is written for
it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prefix
|
str
|
Only keys starting with it. Default: all. |
''
|
bucket
|
str | None
|
Bucket; |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
Objects rewritten by this call. |
Raises:
| Type | Description |
|---|---|
ValueError
|
When the client has no |
StorageIntegrityException
|
When an object fails to decrypt — its key is no longer in the ring, or the file is damaged. |
OSError
|
When a file cannot be read or written. |
IntegrationDisabledException
|
When built with |
list_buckets
async
¶
List the buckets that hold at least one directory on disk.
Returns:
| Type | Description |
|---|---|
list[str]
|
list[str]: Bucket names, sorted; |
Raises:
| Type | Description |
|---|---|
IntegrationDisabledException
|
When built with |
download_response
async
¶
download_response(
key: str,
*,
request: Request | None = None,
bucket: str | None = None,
filename: str | None = None,
media_type: str | None = None,
as_attachment: bool = True,
chunk_size: int = LOCAL_STORAGE_CHUNK_SIZE,
cache_control: str | None = None,
headers: dict[str, str] | None = None,
) -> StreamingResponse
Stream an object as a download response, Range included.
Same behaviour as
:meth:AsyncMinIOClient.download_response
<tempest_fastapi_sdk.storage.AsyncMinIOClient.download_response>:
both delegate to the same function.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
Object key. |
required |
request
|
Request | None
|
The incoming request, whose |
None
|
bucket
|
str | None
|
Source bucket. |
None
|
filename
|
str | None
|
Name presented to the client. |
None
|
media_type
|
str | None
|
Content type; defaults to the stored one. |
None
|
as_attachment
|
bool
|
|
True
|
chunk_size
|
int
|
Bytes per streamed chunk. |
LOCAL_STORAGE_CHUNK_SIZE
|
cache_control
|
str | None
|
|
None
|
headers
|
dict[str, str] | None
|
Extra response headers. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
StreamingResponse |
StreamingResponse
|
|
With encryption_keys the response is the decrypted object;
Content-Length, Range and Content-Range count plaintext
bytes, and a range decrypts only the blocks it covers.
Raises:
| Type | Description |
|---|---|
LocalObjectNotFoundError
|
When the object is not stored. |
StorageIntegrityException
|
When the first block served fails to
verify (see :meth: |
IntegrationDisabledException
|
When built with |
bound_purpose
¶
Bind a link's extra query parameters into its signing purpose.
:func:~tempest_fastapi_sdk.utils.signed_url.sign_path covers the path
and the expiry only. The download overrides and the upload limits ride
in the query, so they are folded into the purpose instead: the route
rebuilds the purpose from the parameters it received, and any change to
them — a bigger max_bytes, another media_type — verifies as a
different purpose and fails. With no parameters the purpose is
unchanged, so a plain link signed before these existed still verifies.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
purpose
|
str
|
The base purpose. |
required |
params
|
dict[str, str]
|
The parameters the link carries. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
|
str
|
sorted and URL-encoded. |
PresignedPost
dataclass
¶
A form upload the store accepts only within the signed limits.
The browser sends multipart/form-data to :attr:url with every
pair of :attr:fields and then the file in :data:POST_FILE_FIELD.
A body outside [min_bytes, max_bytes], a different key or a
different Content-Type is refused by the store itself.
Attributes:
| Name | Type | Description |
|---|---|---|
url |
str
|
Where the form is posted. |
fields |
dict[str, str]
|
Form fields to send, unchanged, before the file. |
max_bytes |
int
|
The largest file the store accepts. |
LocalObjectNotFoundError
¶
Bases: FileNotFoundError
Raised when a key is not stored in the bucket.
A :class:FileNotFoundError — so except OSError catches it — with
the S3 error code beside it, so code written against S3Error.code
can branch the same way.
Attributes:
| Name | Type | Description |
|---|---|---|
code |
str
|
Always |
bucket |
str
|
The bucket that was read. |
key |
str
|
The key that is missing. |
Build the error.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bucket
|
str
|
The bucket that was read. |
required |
key
|
str
|
The key that is missing. |
required |
LocalObjectCipher
¶
The key ring of an encrypted local store.
The first key (insertion order) seals new objects; any key opens the
objects sealed with it, by the id in their header — which is how a key
is rotated: put the new one first, keep the old one until
:meth:~tempest_fastapi_sdk.storage.LocalObjectStorageClient.reencrypt
has rewritten everything.
Attributes:
| Name | Type | Description |
|---|---|---|
write_key_id |
str
|
Id of the key new objects are sealed with. |
Validate the keys and build one AES-GCM instance per key.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
keys
|
Mapping[str, bytes]
|
Key id to 32-byte key; at least one. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
ImportError
|
When |
has_key
¶
Tell whether the ring holds a key.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key_id
|
str
|
The key id. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
|
encryptor
¶
Start sealing a new object with the write key.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
object_name
|
str
|
|
required |
Returns:
| Name | Type | Description |
|---|---|---|
BlockEncryptor |
BlockEncryptor
|
The encryptor, with a fresh nonce prefix. |
reader
¶
reader(
handle: IO[bytes], header: EncryptedHeader, *, file_size: int, object_name: str
) -> EncryptedObjectReader
Open the blocks of a stored object for reading.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
handle
|
IO[bytes]
|
The open file. |
required |
header
|
EncryptedHeader
|
Its header, already read. |
required |
file_size
|
int
|
The file's size on disk. |
required |
object_name
|
str
|
|
required |
Returns:
| Name | Type | Description |
|---|---|---|
EncryptedObjectReader |
EncryptedObjectReader
|
The reader. |
Raises:
| Type | Description |
|---|---|
StorageIntegrityException
|
|
make_local_storage_router
¶
make_local_storage_router(
client: LocalObjectStorageClient,
*,
as_attachment: bool = False,
cache_control: str | None = "private, no-store",
) -> APIRouter
Build the GET/PUT/POST routes for a local store's signed links.
GET {route_prefix}/{bucket}/{key}verifies a download signature and streams the object with its stored content type, honouringRangeand the validators (206/304/416) the same way :meth:AsyncMinIOClient.download_response <tempest_fastapi_sdk.storage.AsyncMinIOClient.download_response>does. A missing object answers404 NOT_FOUND. A link signed withfilename/media_type/as_attachmentanswers with those, the way S3 answers a link with signedresponse-*overrides.PUT {route_prefix}/{bucket}/{key}verifies an upload signature and stores the raw body with the request'sContent-Type. AContent-Lengthover :attr:LocalObjectStorageClient.max_upload_bytesis refused before reading; without it the body is counted while it streams and cut at the cap —413 FILE_TOO_LARGEeither way, and nothing is stored. Success answers200with theETag, as S3 does.POST {route_prefix}/{bucket}/{key}answers a :meth:LocalObjectStorageClient.presigned_post_policyform. The file must fit the signed[min_bytes, max_bytes]—413 FILE_TOO_LARGE/400 FILE_TOO_SMALLotherwise — and thekeyandContent-Typefields must match the signed ones (403 SIGNED_URL_INVALID). Success answers204with theETag, as S3 does. Reading the form needspython-multipart([upload]).
A tampered, unsigned or wrong-purpose link answers
403 SIGNED_URL_INVALID, an expired one 403 SIGNED_URL_EXPIRED.
Both routes stay out of the OpenAPI schema.
With encryption_keys on the client the routes do not change shape:
PUT and POST store the body encrypted, the caps count the
plaintext, and GET (Range included) answers the plaintext. A
stored file whose first served block fails its check answers
500 STORAGE_INTEGRITY_ERROR with no byte of it; a later block that
fails cuts the connection after the blocks that verified.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
client
|
LocalObjectStorageClient
|
The store whose links to serve. |
required |
as_attachment
|
bool
|
|
False
|
cache_control
|
str | None
|
|
'private, no-store'
|
Returns:
| Name | Type | Description |
|---|---|---|
APIRouter |
APIRouter
|
Router with |
APIRouter
|
the app root. |
make_tus_router
¶
make_tus_router(
store: TusStore,
*,
prefix: str = "/api/uploads",
max_size: int = DEFAULT_TUS_MAX_SIZE,
max_chunk_size: int = DEFAULT_TUS_MAX_CHUNK_SIZE,
expiration: timedelta | None = DEFAULT_TUS_EXPIRATION,
current_user_id: Callable[..., Any] | None = None,
on_complete: TusCompleteCallback | None = None,
max_uploads_per_owner: int | None = None,
max_bytes_per_owner: int | None = None,
body_read_timeout: timedelta = DEFAULT_TUS_BODY_READ_TIMEOUT,
tags: list[str] | None = None,
include_in_schema: bool = True,
) -> APIRouter
Build the tus routes createResumableUpload talks to.
Every response of these routes carries Tus-Resumable: 1.0.0, and so
does every refusal raised while handling them (the router's errors and a
401/403 from current_user_id); an unhandled 500 is
answered by the app without it. Errors use the SDK envelope
(detail/code/details) through
:class:~tempest_fastapi_sdk.AppException, so mount the app with
:func:~tempest_fastapi_sdk.register_exception_handlers as usual.
A PATCH takes the upload's lock before reading its body; a second
PATCH or DELETE arriving meanwhile answers 409
TUS_UPLOAD_LOCKED at once, so one upload never has two bodies spooled.
Under the lock: owner (404), expiry (410), already complete
(409 TUS_UPLOAD_COMPLETED), offset (409), size (413),
the store's min_chunk_size (400). The PATCH that stores the
last byte finalizes the upload and calls on_complete — exactly once
per upload. An empty PATCH writes nothing and does not renew the
expiry.
The lock lives on the store instance, in this process. Two replicas behind a load balancer can still race on one upload; route an upload's requests to one replica (sticky sessions on the upload path) when you run more than one.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
store
|
TusStore
|
Where uploads live — :class: |
required |
prefix
|
str
|
The creation endpoint; uploads live under
|
'/api/uploads'
|
max_size
|
int
|
Largest |
DEFAULT_TUS_MAX_SIZE
|
max_chunk_size
|
int
|
Largest |
DEFAULT_TUS_MAX_CHUNK_SIZE
|
expiration
|
timedelta | None
|
How long an incomplete upload stays
resumable after creation or its last |
DEFAULT_TUS_EXPIRATION
|
current_user_id
|
Callable[..., Any] | None
|
FastAPI dependency
resolving the caller's id as |
None
|
on_complete
|
TusCompleteCallback | None
|
Awaited once with the
upload and the store when the last byte is stored. If it raises,
the request answers |
None
|
max_uploads_per_owner
|
int | None
|
Most unfinished, unexpired uploads
one owner may hold; a creation past it answers |
None
|
max_bytes_per_owner
|
int | None
|
Most declared bytes
( |
None
|
body_read_timeout
|
timedelta
|
Longest wait for the next piece of a
|
DEFAULT_TUS_BODY_READ_TIMEOUT
|
tags
|
list[str] | None
|
OpenAPI tags. Defaults to |
None
|
include_in_schema
|
bool
|
Whether the routes appear in OpenAPI. |
True
|
Returns:
| Name | Type | Description |
|---|---|---|
APIRouter |
APIRouter
|
Ready for |
TusCompleteCallback
¶
Bases: Protocol
Called exactly once per upload, after its last byte is stored and finalized.
Receives the upload and the store, so it can read the file with
:meth:TusStore.stream <tempest_fastapi_sdk.storage.tus.TusStore.stream>
(or :meth:LocalTusStore.data_path
<tempest_fastapi_sdk.storage.tus.LocalTusStore.data_path> /
:meth:S3TusStore.object_key
<tempest_fastapi_sdk.storage.tus.S3TusStore.object_key>) and register,
move or delete it. Runs inside the request that sent the last chunk,
under the upload's lock, before the 204; a later PATCH to the
complete upload answers 409 without calling it. Whatever it returns
is discarded, and it may call :meth:TusStore.delete
<tempest_fastapi_sdk.storage.tus.TusStore.delete> — the router then
leaves the record deleted.
TusStore
¶
Bases: ABC
Persistence contract of :func:~tempest_fastapi_sdk.storage.tus.make_tus_router.
Writes to one upload are serialized by a lock table that lives on the
store instance and is shared by every router built over it and by
:meth:purge_expired; it covers one process. A method given an id that
fails :func:valid_upload_id treats it as absent instead of building a
path or key from it.
Subclass it to keep uploads elsewhere; :meth:purge_expired and
:meth:list_uploads come for free from the abstract methods.
min_chunk_size
class-attribute
instance-attribute
¶
Smallest chunk the router accepts, except the one that ends the upload.
create
abstractmethod
async
¶
create(upload: TusUpload) -> None
Persist a new upload with no bytes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
upload
|
TusUpload
|
The record, |
required |
save
abstractmethod
async
¶
save(upload: TusUpload) -> None
Overwrite an upload's record.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
upload
|
TusUpload
|
The record to persist. |
required |
write
abstractmethod
async
¶
write(upload: TusUpload, data: BinaryIO, size: int) -> None
Store size bytes of data at upload.offset.
Does not change the record: the router saves the new offset after this returns, so a failure here leaves the upload where it was.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
upload
|
TusUpload
|
The upload, with the offset the bytes start at. |
required |
data
|
BinaryIO
|
A stream positioned at the first byte. |
required |
size
|
int
|
How many bytes to take from it. |
required |
finalize
abstractmethod
async
¶
finalize(upload: TusUpload) -> None
Turn the stored chunks into the finished file.
Called once offset == length, before on_complete.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
upload
|
TusUpload
|
The complete upload. |
required |
discard_parts
async
¶
discard_parts(upload: TusUpload) -> None
Drop whatever :meth:finalize assembled from, once the record says complete.
Called after the complete record is saved, so a failure here never leaves an upload that cannot finish; a store with nothing to drop keeps this no-op.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
upload
|
TusUpload
|
The complete upload. |
required |
stream
abstractmethod
¶
Read a finished upload's bytes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
upload_id
|
str
|
The id of a finalized upload. |
required |
chunk_size
|
int
|
Bytes per yielded chunk. |
TUS_STREAM_CHUNK_SIZE
|
Returns:
| Type | Description |
|---|---|
AsyncIterator[bytes]
|
AsyncIterator[bytes]: The file, in order. |
delete
abstractmethod
async
¶
Remove an upload's bytes, record and idempotency entry.
Idempotent: an absent upload is not an error.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
upload_id
|
str
|
The id. |
required |
list_ids
abstractmethod
async
¶
List the ids of every stored upload.
Returns:
| Type | Description |
|---|---|
list[str]
|
list[str]: The ids; |
find_idempotent
abstractmethod
async
¶
Look up the upload a creation Idempotency-Key produced.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
digest
|
str
|
SHA-256 hex of owner and key. |
required |
Returns:
| Type | Description |
|---|---|
str | None
|
str | None: The upload id, or |
remember_idempotent
abstractmethod
async
¶
Record which upload a creation Idempotency-Key produced.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
digest
|
str
|
SHA-256 hex of owner and key. |
required |
upload_id
|
str
|
The upload it created. |
required |
purge_expired
async
¶
Delete every incomplete upload past its expires_at.
Run it on a schedule (a TaskIQ periodic task, a cron). Each upload is
re-read under the same per-upload lock the router writes under, and one
with a request in progress is skipped. A complete
upload is never purged, notified or not: its bytes belong to the
service, which deletes them with :meth:delete when done.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
now
|
datetime | None
|
The moment to compare with. Defaults to the current UTC time. |
None
|
Returns:
| Type | Description |
|---|---|
list[str]
|
list[str]: The ids deleted; |
LocalTusStore
¶
Bases: TusStore
Keep tus uploads in a directory of the server.
Layout under root: <id>.json holds the record (replaced
atomically with os.replace), <id>.bin the bytes, written in place
at the offset with fsync, and _idempotency/<digest> the upload id a
creation key produced. File names come from the generated id only, never
from Upload-Metadata, so a client name cannot escape root.
Every call runs its blocking I/O in asyncio.to_thread.
Attributes:
| Name | Type | Description |
|---|---|---|
root |
Path
|
The directory, created on first use. |
Initialize the store.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
root
|
str | Path
|
Directory to keep uploads in. Created with its parents when missing. |
required |
data_path
¶
Path of an upload's bytes on disk.
After the upload completes this is the finished file, ready for the service to move or read.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
upload_id
|
str
|
The upload id. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
Path |
Path
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
create
async
¶
create(upload: TusUpload) -> None
Create the empty data file and the record.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
upload
|
TusUpload
|
The new record. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
load
async
¶
load(upload_id: str) -> TusUpload | None
Read a record from disk.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
upload_id
|
str
|
The id. |
required |
Returns:
| Type | Description |
|---|---|
TusUpload | None
|
TusUpload | None: The record, or |
save
async
¶
save(upload: TusUpload) -> None
Replace a record on disk.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
upload
|
TusUpload
|
The record. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
write
async
¶
write(upload: TusUpload, data: BinaryIO, size: int) -> None
Write bytes at the offset, cutting anything a crashed write left past it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
upload
|
TusUpload
|
The upload. |
required |
data
|
BinaryIO
|
The chunk stream. |
required |
size
|
int
|
Bytes to copy. |
required |
finalize
async
¶
finalize(upload: TusUpload) -> None
Nothing to assemble: the data file already is the finished file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
upload
|
TusUpload
|
The complete upload. |
required |
stream
async
¶
Read the data file in chunks.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
upload_id
|
str
|
The upload id. |
required |
chunk_size
|
int
|
Bytes per chunk. |
TUS_STREAM_CHUNK_SIZE
|
Yields:
| Name | Type | Description |
|---|---|---|
bytes |
AsyncIterator[bytes]
|
The next chunk. |
delete
async
¶
Remove the data file, the record and the idempotency entry.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
upload_id
|
str
|
The id. |
required |
list_ids
async
¶
List the ids that have a record file.
Returns:
| Type | Description |
|---|---|
list[str]
|
list[str]: The ids, sorted; |
list[str]
|
missing. |
find_idempotent
async
¶
Read an idempotency entry.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
digest
|
str
|
SHA-256 hex digest. |
required |
Returns:
| Type | Description |
|---|---|
str | None
|
str | None: The upload id, or |
remember_idempotent
async
¶
Write an idempotency entry atomically.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
digest
|
str
|
SHA-256 hex digest. |
required |
upload_id
|
str
|
The upload it created. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
When the digest or the id is malformed. |
S3TusStore
¶
S3TusStore(
client: TusObjectClient,
*,
bucket: str | None = None,
prefix: str = "tus/",
min_chunk_size: int = DEFAULT_S3_TUS_MIN_CHUNK_SIZE,
)
Bases: TusStore
Keep tus uploads in an S3-compatible bucket.
See the module docstring for the layout and why chunks are separate
objects. Install the [minio] extra for
:class:~tempest_fastapi_sdk.storage.AsyncMinIOClient.
Attributes:
| Name | Type | Description |
|---|---|---|
client |
TusObjectClient
|
The object-storage client. |
bucket |
str | None
|
Bucket override; |
prefix |
str
|
Key prefix every object of this store lives under. |
min_chunk_size |
int
|
Smallest non-final chunk the router accepts. |
Initialize the store.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
client
|
TusObjectClient
|
The object-storage client, e.g. an
:class: |
required |
bucket
|
str | None
|
Bucket override. |
None
|
prefix
|
str
|
Key prefix, |
'tus/'
|
min_chunk_size
|
int
|
Smallest |
DEFAULT_S3_TUS_MIN_CHUNK_SIZE
|
object_key
¶
Key of a finished upload's file, for the service to copy or serve.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
upload_id
|
str
|
The upload id. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
create
async
¶
create(upload: TusUpload) -> None
Write the record of a new upload.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
upload
|
TusUpload
|
The record. |
required |
load
async
¶
load(upload_id: str) -> TusUpload | None
Read a record from the bucket.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
upload_id
|
str
|
The id. |
required |
Returns:
| Type | Description |
|---|---|
TusUpload | None
|
TusUpload | None: The record, or |
save
async
¶
save(upload: TusUpload) -> None
Overwrite a record in the bucket.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
upload
|
TusUpload
|
The record. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
write
async
¶
write(upload: TusUpload, data: BinaryIO, size: int) -> None
Store a chunk as its own object, keyed by its offset.
A chunk an earlier attempt wrote at the same offset is replaced.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
upload
|
TusUpload
|
The upload. |
required |
data
|
BinaryIO
|
The chunk stream. |
required |
size
|
int
|
Bytes in it. |
required |
finalize
async
¶
finalize(upload: TusUpload) -> None
Concatenate the chunks into <prefix><id>/data.
Only the chain of chunks that starts at 0 and ends at
upload.length is read; a chunk outside it (an earlier attempt at
an offset that a later write superseded) is skipped. The chunks stay
until :meth:discard_parts, which the router calls after saving the
complete record: a failure here, or before that save, leaves every
chunk in place, and the retried last PATCH assembles again.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
upload
|
TusUpload
|
The complete upload. |
required |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
When the stored chunks do not cover the upload. |
discard_parts
async
¶
discard_parts(upload: TusUpload) -> None
Delete the chunk objects of a complete upload.
Runs after the router saved the complete record, so a failure here
leaves stray chunks — removed by :meth:delete — but never an upload
stuck before completion.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
upload
|
TusUpload
|
The complete upload. |
required |
stream
async
¶
Read a finished upload's file from the bucket.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
upload_id
|
str
|
The upload id. |
required |
chunk_size
|
int
|
Bytes per chunk. |
TUS_STREAM_CHUNK_SIZE
|
Yields:
| Name | Type | Description |
|---|---|---|
bytes |
AsyncIterator[bytes]
|
The next chunk. |
delete
async
¶
Remove every object of the upload and its idempotency entry.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
upload_id
|
str
|
The id. |
required |
list_ids
async
¶
List the ids that have a record object.
Returns:
| Type | Description |
|---|---|
list[str]
|
list[str]: The ids, sorted; |
find_idempotent
async
¶
Read an idempotency entry from the bucket.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
digest
|
str
|
SHA-256 hex digest. |
required |
Returns:
| Type | Description |
|---|---|
str | None
|
str | None: The upload id, or |
remember_idempotent
async
¶
Write an idempotency entry to the bucket.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
digest
|
str
|
SHA-256 hex digest. |
required |
upload_id
|
str
|
The upload it created. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
When the digest or the id is malformed. |
TusObjectClient
¶
Bases: Protocol
The object-storage calls :class:S3TusStore makes.
:class:~tempest_fastapi_sdk.storage.AsyncMinIOClient,
:class:~tempest_fastapi_sdk.storage.BucketRoutedMinIOClient,
:class:~tempest_fastapi_sdk.storage.LocalObjectStorageClient and
:class:~tempest_fastapi_sdk.testing.fakes.FakeObjectStorageClient all satisfy
it. A missing object must raise :class:FileNotFoundError or an error
whose code is "NoSuchKey".
put_object
async
¶
put_object(
key: str,
data: bytes | BinaryIO,
/,
*,
bucket: str | None = None,
content_type: str = "application/octet-stream",
length: int | None = None,
) -> str
Store one object.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
Object key. |
required |
data
|
bytes | BinaryIO
|
Payload. |
required |
bucket
|
str | None
|
Target bucket. |
None
|
content_type
|
str
|
MIME type. |
'application/octet-stream'
|
length
|
int | None
|
Payload size, required for a stream. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The ETag. |
stream_object
async
¶
stream_object(
key: str, /, *, bucket: str | None = None, chunk_size: int = 64 * 1024
) -> AsyncIterator[bytes]
Read one object in chunks.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
Object key. |
required |
bucket
|
str | None
|
Source bucket. |
None
|
chunk_size
|
int
|
Bytes per chunk. |
64 * 1024
|
Returns:
| Type | Description |
|---|---|
AsyncIterator[bytes]
|
AsyncIterator[bytes]: The payload. |
list_objects
async
¶
List keys under a prefix, recursively.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prefix
|
str
|
Key prefix. |
''
|
bucket
|
str | None
|
Source bucket. |
None
|
Returns:
| Type | Description |
|---|---|
list[str]
|
list[str]: The keys. |
remove_object
async
¶
Delete one object; absent is not an error.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
Object key. |
required |
bucket
|
str | None
|
Target bucket. |
None
|
TusUpload
dataclass
¶
TusUpload(
id: str,
length: int,
offset: int = 0,
metadata: dict[str, str] = dict(),
owner: str | None = None,
created_at: datetime = (lambda: now(UTC))(),
expires_at: datetime | None = None,
idempotency_digest: str | None = None,
notified: bool = False,
)
One resumable upload, as a tus store keeps it.
The record is the authority on how many bytes are stored: a chunk is
written first and the record saved after, so a crash between the two
leaves offset at the last confirmed byte and the next PATCH
overwrites whatever was half-written past it.
Attributes:
| Name | Type | Description |
|---|---|---|
id |
str
|
Unguessable id, the last segment of the upload URL. |
length |
int
|
Total size the client declared in |
offset |
int
|
Bytes stored so far. |
metadata |
dict[str, str]
|
Decoded |
owner |
str | None
|
|
created_at |
datetime
|
Creation time, UTC. |
expires_at |
datetime | None
|
When an incomplete upload stops being
resumable. Renewed by every accepted |
idempotency_digest |
str | None
|
SHA-256 of owner and
|
notified |
bool
|
Whether |
completed
property
¶
Whether every declared byte is stored.
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
|
filename
property
¶
The client's file name, sanitized for use in a path or header.
Read from the filename metadata key, then name, through
:func:sanitize_upload_filename.
Returns:
| Type | Description |
|---|---|
str | None
|
str | None: The safe name, or |
is_expired
¶
Whether this upload is incomplete and past expires_at.
A complete upload never expires: its bytes are the service's now.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
now
|
datetime | None
|
The moment to compare with. Defaults to the current UTC time. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
|
to_json
¶
Serialize the record for a store.
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
A JSON object. |
PutObjectItem
dataclass
¶
PutObjectItem(
key: str,
data: bytes | BinaryIO,
content_type: str = "application/octet-stream",
metadata: dict[str, str] | None = None,
length: int | None = None,
part_size: int = 10 * 1024 * 1024,
)
One object to upload in an :meth:AsyncMinIOClient.put_objects batch.
Mirrors the per-object arguments of :meth:AsyncMinIOClient.put_object
so a single batch can carry heterogeneous payloads — different content
types, metadata, or unknown-length streams.
Attributes:
| Name | Type | Description |
|---|---|---|
key |
str
|
Destination object key. |
data |
bytes | BinaryIO
|
Payload. |
content_type |
str
|
MIME type. |
metadata |
dict[str, str] | None
|
User metadata stored under the
|
length |
int | None
|
Payload size in bytes. Required for file-like
data; pass |
part_size |
int
|
Multipart chunk size in bytes. At least 5 MiB. Default 10 MiB. |
TUS_CORS_ALLOW_HEADERS
module-attribute
¶
TUS_CORS_ALLOW_HEADERS: tuple[str, ...] = (
"Authorization",
"Content-Type",
"Idempotency-Key",
"Tus-Resumable",
"Upload-Length",
"Upload-Metadata",
"Upload-Offset",
"X-CSRF-Token",
)
Request headers createResumableUpload sends.
Pass to CORSMiddleware(allow_headers=...).
TUS_CORS_EXPOSE_HEADERS
module-attribute
¶
TUS_CORS_EXPOSE_HEADERS: tuple[str, ...] = (
"Location",
"Tus-Max-Size",
"Tus-Resumable",
"Tus-Version",
"Upload-Expires",
"Upload-Length",
"Upload-Metadata",
"Upload-Offset",
)
Response headers a cross-origin client must be allowed to read.
Pass to CORSMiddleware(expose_headers=...). Without Location and
Upload-Offset there, a browser on another origin gets null from
getResponseHeader and the client cannot find the upload it created.