Skip to content

Uploads

File and image fields store their files through a fastapi-storages backend passed as Admin(storage=...); see File Uploads for the column types and the per-record download route. S3StorageBackend needs the s3 extra (pip install 'hyper-admin[s3]'); the image helpers need Pillow.

Name What it does
S3StorageBackend An S3-compatible storage backend configured per instance or from HYPERADMIN_AWS_* settings
validate_upload Checks an UploadFile against allowed MIME types and a size limit; raises FileValidationError
prepare_image_upload Rewrites an uploaded image upright when its EXIF orientation asks for it and returns its metadata; raises ImageTooLargeError above max_pixels
extract_metadata Width, height, format and EXIF orientation of an image without decoding its pixels, or None for a non-image
auto_rotate Applies the EXIF orientation to a Pillow image
generate_thumbnail Makes a thumbnail of a stored image once and returns its name, or a placeholder icon when the file cannot be read

API Reference

hyperadmin.uploads.S3StorageBackend

Bases: S3Storage

S3Storage configured per instance, for AWS S3 and S3-compatible services.

fastapi_storages.S3Storage reads its configuration from AWS_* environment variables when the module is imported. This subclass takes the same configuration as keyword arguments (or from settings via :meth:from_settings), so two backends can point at different buckets and nothing is read at import time.

Parameters:

Name Type Description Default
bucket_name str

The bucket objects are written to.

required
access_key_id str | None

Static credentials. When unset, boto3's own credential chain applies (profiles, instance and task roles, AWS_* env).

None
secret_access_key str | None

See access_key_id.

None
region str | None

The region name ("eu-central-1"). Optional for services that ignore it (MinIO) but required by AWS without a profile default.

None
endpoint_url str | None

http(s)://host[:port] of an S3-compatible service (MinIO, R2, Hetzner, Spaces). Unset for AWS S3. http:// turns SSL off for that endpoint.

None
custom_domain str | None

Serve object URLs from this host instead of the endpoint (a CDN or an R2 public bucket domain). URLs are then not signed.

None
querystring_auth bool

Sign object URLs (presigned, time-limited; default). Set False only for a public-read bucket.

True
default_acl str | None

ACL set on every written object ("public-read"). Unset (default) keeps objects private and sends no ACL, which services without ACL support (R2) require.

None
client Any

An existing boto3 S3 client to use instead of building one (tests, custom sessions). The other connection arguments are then only used to build URLs.

None
Source code in src/hyperadmin/uploads/storage.py
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
class S3StorageBackend(S3Storage):
    """``S3Storage`` configured per instance, for AWS S3 and S3-compatible services.

    ``fastapi_storages.S3Storage`` reads its configuration from ``AWS_*``
    environment variables when the module is imported. This subclass takes the
    same configuration as keyword arguments (or from settings via
    :meth:`from_settings`), so two backends can point at different buckets and
    nothing is read at import time.

    Args:
        bucket_name: The bucket objects are written to.
        access_key_id: Static credentials. When unset, boto3's own credential
            chain applies (profiles, instance and task roles, ``AWS_*`` env).
        secret_access_key: See ``access_key_id``.
        region: The region name (``"eu-central-1"``). Optional for services that
            ignore it (MinIO) but required by AWS without a profile default.
        endpoint_url: ``http(s)://host[:port]`` of an S3-compatible service
            (MinIO, R2, Hetzner, Spaces). Unset for AWS S3. ``http://`` turns SSL
            off for that endpoint.
        custom_domain: Serve object URLs from this host instead of the endpoint
            (a CDN or an R2 public bucket domain). URLs are then not signed.
        querystring_auth: Sign object URLs (presigned, time-limited; default).
            Set ``False`` only for a public-read bucket.
        default_acl: ACL set on every written object (``"public-read"``).
            Unset (default) keeps objects private and sends no ACL, which
            services without ACL support (R2) require.
        client: An existing boto3 S3 client to use instead of building one
            (tests, custom sessions). The other connection arguments are then
            only used to build URLs.
    """

    def __init__(  # noqa: PLR0913 - one keyword per S3 connection setting
        self,
        *,
        bucket_name: str,
        access_key_id: str | None = None,
        secret_access_key: str | None = None,
        region: str | None = None,
        endpoint_url: str | None = None,
        custom_domain: str | None = None,
        querystring_auth: bool = True,
        default_acl: str | None = None,
        client: Any = None,
    ) -> None:
        if not bucket_name:
            msg = "S3StorageBackend requires a bucket name"
            raise ValueError(msg)
        scheme, host = _split_endpoint(endpoint_url)
        self.bucket_name = bucket_name
        self.region = region
        self.custom_domain = custom_domain
        self.querystring_auth = querystring_auth
        self.default_acl = default_acl
        self._http_scheme = scheme
        endpoint = f"{scheme}://{host}" if host else None
        if client is None:
            client = _s3_client(
                **_client_kwargs(
                    use_ssl=scheme == "https",
                    endpoint=endpoint,
                    region=region,
                    access_key_id=access_key_id,
                    secret_access_key=secret_access_key,
                )
            )
        self._s3 = client
        self._url = endpoint or str(client.meta.endpoint_url)

    @classmethod
    def from_settings(cls, settings: HyperAdminSettings, *, client: Any = None) -> S3StorageBackend:
        """Build a backend from the ``aws_*`` settings (``HYPERADMIN_AWS_*`` / ``AWS_*`` env).

        Raises:
            ValueError: ``aws_s3_bucket_name`` is unset.
        """
        if not settings.aws_s3_bucket_name:
            msg = (
                "S3 storage requires a bucket: set aws_s3_bucket_name "
                "(HYPERADMIN_AWS_S3_BUCKET_NAME or AWS_S3_BUCKET_NAME)"
            )
            raise ValueError(msg)
        secret = settings.aws_secret_access_key
        return cls(
            bucket_name=settings.aws_s3_bucket_name,
            access_key_id=settings.aws_access_key_id,
            secret_access_key=secret.get_secret_value() if secret is not None else None,
            region=settings.aws_s3_region,
            endpoint_url=settings.aws_s3_endpoint_url,
            custom_domain=settings.aws_s3_custom_domain,
            querystring_auth=settings.aws_s3_querystring_auth,
            default_acl=settings.aws_s3_default_acl,
            client=client,
        )

    def get_name(self, name: str) -> str:
        """Return the object key for ``name``: the basename sanitised, directories kept."""
        path = PurePosixPath(name.replace("\\", "/"))
        safe = secure_filename(path.name)
        return str(path.parent / safe) if safe else name

    def get_path(self, name: str) -> str:
        """Return the URL of the object ``name``.

        Served from ``custom_domain`` when set, otherwise presigned through the
        client when ``querystring_auth`` is on (default), otherwise the plain
        path-style URL under the endpoint.
        """
        key = self.get_name(name)
        if self.custom_domain:
            return f"{self._http_scheme}://{self.custom_domain}/{key}"
        if self.querystring_auth:
            params = {"Bucket": self.bucket_name, "Key": key}
            return str(self._s3.generate_presigned_url("get_object", Params=params))
        return f"{self._url}/{self.bucket_name}/{key}"

    def get_size(self, name: str) -> int:
        """Return the object size in bytes (one ``HeadObject`` call)."""
        response = self._s3.head_object(Bucket=self.bucket_name, Key=self.get_name(name))
        return int(response["ContentLength"])

    def write(self, file: BinaryIO, name: str) -> str:
        """Upload ``file`` as ``name`` and return the object key.

        No ``ACL`` parameter is sent when ``default_acl`` is unset: boto3
        rejects ``ACL=None``, and services such as R2 reject any ACL at all.
        """
        file.seek(0, 0)
        key = self.get_name(name)
        content_type, _ = mimetypes.guess_type(key)
        params: dict[str, Any] = {"ContentType": content_type or _DEFAULT_CONTENT_TYPE}
        if self.default_acl:
            params["ACL"] = self.default_acl
        self._s3.upload_fileobj(file, self.bucket_name, key, ExtraArgs=params)
        return key

    def delete(self, name: str) -> None:
        """Delete the object ``name`` from the bucket."""
        self._s3.delete_object(Bucket=self.bucket_name, Key=self.get_name(name))

delete(name)

Delete the object name from the bucket.

Source code in src/hyperadmin/uploads/storage.py
210
211
212
def delete(self, name: str) -> None:
    """Delete the object ``name`` from the bucket."""
    self._s3.delete_object(Bucket=self.bucket_name, Key=self.get_name(name))

from_settings(settings, *, client=None) classmethod

Build a backend from the aws_* settings (HYPERADMIN_AWS_* / AWS_* env).

Raises:

Type Description
ValueError

aws_s3_bucket_name is unset.

Source code in src/hyperadmin/uploads/storage.py
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
@classmethod
def from_settings(cls, settings: HyperAdminSettings, *, client: Any = None) -> S3StorageBackend:
    """Build a backend from the ``aws_*`` settings (``HYPERADMIN_AWS_*`` / ``AWS_*`` env).

    Raises:
        ValueError: ``aws_s3_bucket_name`` is unset.
    """
    if not settings.aws_s3_bucket_name:
        msg = (
            "S3 storage requires a bucket: set aws_s3_bucket_name "
            "(HYPERADMIN_AWS_S3_BUCKET_NAME or AWS_S3_BUCKET_NAME)"
        )
        raise ValueError(msg)
    secret = settings.aws_secret_access_key
    return cls(
        bucket_name=settings.aws_s3_bucket_name,
        access_key_id=settings.aws_access_key_id,
        secret_access_key=secret.get_secret_value() if secret is not None else None,
        region=settings.aws_s3_region,
        endpoint_url=settings.aws_s3_endpoint_url,
        custom_domain=settings.aws_s3_custom_domain,
        querystring_auth=settings.aws_s3_querystring_auth,
        default_acl=settings.aws_s3_default_acl,
        client=client,
    )

get_name(name)

Return the object key for name: the basename sanitised, directories kept.

Source code in src/hyperadmin/uploads/storage.py
169
170
171
172
173
def get_name(self, name: str) -> str:
    """Return the object key for ``name``: the basename sanitised, directories kept."""
    path = PurePosixPath(name.replace("\\", "/"))
    safe = secure_filename(path.name)
    return str(path.parent / safe) if safe else name

get_path(name)

Return the URL of the object name.

Served from custom_domain when set, otherwise presigned through the client when querystring_auth is on (default), otherwise the plain path-style URL under the endpoint.

Source code in src/hyperadmin/uploads/storage.py
175
176
177
178
179
180
181
182
183
184
185
186
187
188
def get_path(self, name: str) -> str:
    """Return the URL of the object ``name``.

    Served from ``custom_domain`` when set, otherwise presigned through the
    client when ``querystring_auth`` is on (default), otherwise the plain
    path-style URL under the endpoint.
    """
    key = self.get_name(name)
    if self.custom_domain:
        return f"{self._http_scheme}://{self.custom_domain}/{key}"
    if self.querystring_auth:
        params = {"Bucket": self.bucket_name, "Key": key}
        return str(self._s3.generate_presigned_url("get_object", Params=params))
    return f"{self._url}/{self.bucket_name}/{key}"

get_size(name)

Return the object size in bytes (one HeadObject call).

Source code in src/hyperadmin/uploads/storage.py
190
191
192
193
def get_size(self, name: str) -> int:
    """Return the object size in bytes (one ``HeadObject`` call)."""
    response = self._s3.head_object(Bucket=self.bucket_name, Key=self.get_name(name))
    return int(response["ContentLength"])

write(file, name)

Upload file as name and return the object key.

No ACL parameter is sent when default_acl is unset: boto3 rejects ACL=None, and services such as R2 reject any ACL at all.

Source code in src/hyperadmin/uploads/storage.py
195
196
197
198
199
200
201
202
203
204
205
206
207
208
def write(self, file: BinaryIO, name: str) -> str:
    """Upload ``file`` as ``name`` and return the object key.

    No ``ACL`` parameter is sent when ``default_acl`` is unset: boto3
    rejects ``ACL=None``, and services such as R2 reject any ACL at all.
    """
    file.seek(0, 0)
    key = self.get_name(name)
    content_type, _ = mimetypes.guess_type(key)
    params: dict[str, Any] = {"ContentType": content_type or _DEFAULT_CONTENT_TYPE}
    if self.default_acl:
        params["ACL"] = self.default_acl
    self._s3.upload_fileobj(file, self.bucket_name, key, ExtraArgs=params)
    return key

hyperadmin.uploads.validate_upload(file, *, allowed_types=None, max_size=None)

Validate an uploaded file against size and MIME type constraints.

Parameters:

Name Type Description Default
file UploadFile

The uploaded file to validate.

required
allowed_types list[str] | None

Allowed MIME types (e.g. ["image/jpeg", "image/png"]). When None, all types are accepted.

None
max_size int | None

Maximum file size in bytes. When None, no limit.

None

Raises:

Type Description
FileValidationError

If validation fails.

Source code in src/hyperadmin/uploads/validation.py
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
def validate_upload(
    file: UploadFile,
    *,
    allowed_types: list[str] | None = None,
    max_size: int | None = None,
) -> None:
    """Validate an uploaded file against size and MIME type constraints.

    Args:
        file: The uploaded file to validate.
        allowed_types: Allowed MIME types (e.g. ``["image/jpeg", "image/png"]``).
            When ``None``, all types are accepted.
        max_size: Maximum file size in bytes. When ``None``, no limit.

    Raises:
        FileValidationError: If validation fails.
    """
    if max_size is not None and file.size is not None and file.size > max_size:
        raise FileValidationError(f"File size {file.size} bytes exceeds limit of {max_size} bytes")
    if allowed_types is not None and file.content_type not in allowed_types:
        raise FileValidationError(
            f"File type '{file.content_type}' is not allowed. Accepted: {', '.join(allowed_types)}"
        )

hyperadmin.uploads.FileValidationError

Bases: ValueError

Raised when an uploaded file fails validation checks.

Source code in src/hyperadmin/uploads/validation.py
11
12
class FileValidationError(ValueError):
    """Raised when an uploaded file fails validation checks."""

hyperadmin.uploads.prepare_image_upload(upload, *, max_pixels=MAX_IMAGE_PIXELS)

Normalise an uploaded image in place before the storage column saves it.

This is the hook the form save path calls for ImageType fields. A non-image upload is left untouched. An image whose EXIF orientation says "rotate me" is re-encoded upright, in its original format and with the rest of its EXIF block, straight back into upload.file.

Parameters:

Name Type Description Default
upload UploadFile

The multipart upload; its file is read, possibly rewritten, and always rewound.

required
max_pixels int

Decompression-bomb threshold (width x height).

MAX_IMAGE_PIXELS

Returns:

Type Description
ImageMetadata | None

The metadata of the file as it will be stored, or None for a non-image.

Raises:

Type Description
ImageTooLargeError

The image is larger than max_pixels.

Source code in src/hyperadmin/uploads/images.py
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
def prepare_image_upload(
    upload: UploadFile,
    *,
    max_pixels: int = MAX_IMAGE_PIXELS,
) -> ImageMetadata | None:
    """Normalise an uploaded image in place before the storage column saves it.

    This is the hook the form save path calls for ``ImageType`` fields. A
    non-image upload is left untouched. An image whose EXIF orientation says
    "rotate me" is re-encoded upright, in its original format and with the
    rest of its EXIF block, straight back into ``upload.file``.

    Args:
        upload: The multipart upload; its ``file`` is read, possibly rewritten,
            and always rewound.
        max_pixels: Decompression-bomb threshold (width x height).

    Returns:
        The metadata of the file as it will be stored, or ``None`` for a non-image.

    Raises:
        ImageTooLargeError: The image is larger than ``max_pixels``.
    """
    metadata = extract_metadata(upload, max_pixels=max_pixels)
    if metadata is None or not metadata.needs_rotation:
        return metadata
    stream = upload.file
    encoded = io.BytesIO()
    try:
        with _open_image(stream, max_pixels=max_pixels) as image:
            rotated = auto_rotate(image)
            save_kwargs: dict[str, Any] = {}
            if rotated.info.get("exif"):
                save_kwargs["exif"] = rotated.info["exif"]
            rotated.save(encoded, format=metadata.format, **save_kwargs)
    except _OPEN_ERRORS as exc:
        logger.warning("Upload %r could not be auto-rotated: %s", upload.filename, exc)
        _rewind(stream)
        return metadata
    stream.seek(0)
    stream.truncate()
    stream.write(encoded.getvalue())
    stream.seek(0)
    if hasattr(upload, "size"):
        upload.size = len(encoded.getvalue())
    return ImageMetadata(rotated.width, rotated.height, metadata.format)

hyperadmin.uploads.ImageTooLargeError

Bases: FileValidationError

Raised when an image declares more pixels than max_pixels allows.

Source code in src/hyperadmin/uploads/images.py
56
57
class ImageTooLargeError(FileValidationError):
    """Raised when an image declares more pixels than ``max_pixels`` allows."""

hyperadmin.uploads.extract_metadata(source, *, max_pixels=MAX_IMAGE_PIXELS)

Read dimensions, format and EXIF orientation without decoding pixels.

Parameters:

Name Type Description Default
source str | Path | IO[bytes] | UploadFile

A path, a binary stream or a Starlette UploadFile. Streams are rewound to position 0 afterwards.

required
max_pixels int

Decompression-bomb threshold (width x height).

MAX_IMAGE_PIXELS

Returns:

Type Description
ImageMetadata | None

The metadata, or None when source is not an image Pillow can read.

Raises:

Type Description
ImageTooLargeError

The image is larger than max_pixels.

Source code in src/hyperadmin/uploads/images.py
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
def extract_metadata(
    source: str | Path | IO[bytes] | UploadFile,
    *,
    max_pixels: int = MAX_IMAGE_PIXELS,
) -> ImageMetadata | None:
    """Read dimensions, format and EXIF orientation without decoding pixels.

    Args:
        source: A path, a binary stream or a Starlette ``UploadFile``. Streams
            are rewound to position 0 afterwards.
        max_pixels: Decompression-bomb threshold (width x height).

    Returns:
        The metadata, or ``None`` when ``source`` is not an image Pillow can read.

    Raises:
        ImageTooLargeError: The image is larger than ``max_pixels``.
    """
    stream = _as_stream(source)
    try:
        with _open_image(stream, max_pixels=max_pixels) as image:
            orientation = int(image.getexif().get(_ORIENTATION_TAG, _NORMAL_ORIENTATION))
            return ImageMetadata(image.width, image.height, image.format or "", orientation)
    except ImageTooLargeError:
        raise
    except _OPEN_ERRORS:
        return None
    finally:
        _rewind(stream)

hyperadmin.uploads.auto_rotate(image)

Return image transposed so its pixels match the EXIF orientation.

The returned image carries no orientation tag, so re-saving it will not rotate it twice. An image without an orientation tag is returned as a copy.

Source code in src/hyperadmin/uploads/images.py
154
155
156
157
158
159
160
161
def auto_rotate(image: Image.Image) -> Image.Image:
    """Return ``image`` transposed so its pixels match the EXIF orientation.

    The returned image carries no orientation tag, so re-saving it will not
    rotate it twice. An image without an orientation tag is returned as a copy.
    """
    rotated = ImageOps.exif_transpose(image)
    return image if rotated is None else rotated

hyperadmin.uploads.generate_thumbnail(storage, filename, max_size=DEFAULT_THUMBNAIL_SIZE, *, max_pixels=MAX_IMAGE_PIXELS, placeholder=PLACEHOLDER_THUMBNAIL)

Return a thumbnail of filename that fits inside max_size, making it once.

The thumbnail is written under :data:THUMBNAIL_DIR next to the original, auto-rotated, with its aspect ratio preserved and LANCZOS resampling. A cached thumbnail is reused as long as it is not older than the original.

Parameters:

Name Type Description Default
storage Any

A FileSystemStorage (or compatible object exposing get_path and a _path/path root).

required
filename str

The stored name of the original, as held by the file column.

required
max_size tuple[int, int]

Bounding box (width, height) in pixels.

DEFAULT_THUMBNAIL_SIZE
max_pixels int

Decompression-bomb threshold for the original.

MAX_IMAGE_PIXELS
placeholder str

Value returned when no thumbnail can be produced. The default is a static icon path, not a storage name.

PLACEHOLDER_THUMBNAIL

Returns:

Type Description
str

The storage-relative thumbnail name, or placeholder when the

str

original is missing, outside the storage root, not an image, or too large.

Source code in src/hyperadmin/uploads/images.py
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
def generate_thumbnail(
    storage: Any,
    filename: str,
    max_size: tuple[int, int] = DEFAULT_THUMBNAIL_SIZE,
    *,
    max_pixels: int = MAX_IMAGE_PIXELS,
    placeholder: str = PLACEHOLDER_THUMBNAIL,
) -> str:
    """Return a thumbnail of ``filename`` that fits inside ``max_size``, making it once.

    The thumbnail is written under :data:`THUMBNAIL_DIR` next to the original,
    auto-rotated, with its aspect ratio preserved and LANCZOS resampling. A
    cached thumbnail is reused as long as it is not older than the original.

    Args:
        storage: A ``FileSystemStorage`` (or compatible object exposing
            ``get_path`` and a ``_path``/``path`` root).
        filename: The stored name of the original, as held by the file column.
        max_size: Bounding box ``(width, height)`` in pixels.
        max_pixels: Decompression-bomb threshold for the original.
        placeholder: Value returned when no thumbnail can be produced. The
            default is a static icon path, not a storage name.

    Returns:
        The storage-relative thumbnail name, or ``placeholder`` when the
        original is missing, outside the storage root, not an image, or too large.
    """
    source = resolve_storage_path(storage, filename)
    if source is None or not source.is_file():
        return placeholder
    name = thumbnail_name(filename, max_size)
    target = resolve_storage_path(storage, name)
    if target is None:
        return placeholder
    if target.is_file() and target.stat().st_mtime >= source.stat().st_mtime:
        return name
    encoded = io.BytesIO()
    try:
        with _open_image(source, max_pixels=max_pixels) as image:
            thumb = auto_rotate(image)
            thumb.thumbnail(max_size, Image.Resampling.LANCZOS)
            thumb.save(encoded, format=image.format)
        target.parent.mkdir(parents=True, exist_ok=True)
        target.write_bytes(encoded.getvalue())
    except _THUMBNAIL_ERRORS as exc:
        logger.warning("Thumbnail for %r could not be generated: %s", filename, exc)
        return placeholder
    return name