Skip to content

File

File is a regular AMSDAL Model for managing file uploads and storage. It supports all standard model operations (save(), asave(), objects.filter(), etc.) with automatic storage persistence via pre_create()/pre_update() hooks.

from amsdal.models.core.file import File

Fields

Field Type Default Description
filename str Filename
data bytes \| None None File content (used by DBStorage)
size float \| None None File size in bytes
storage_address Reference \| None None Reference to storage location

Properties

mimetypestr | None

Returns the MIME type based on the filename using the mimetypes module.

storageStorage

Returns the resolved storage backend instance.


Class Methods

File.from_file(file_or_path: Path | BinaryIO) → File

Creates a File from a file path or binary file object.

Raises: ValueError if the path is a directory.

from pathlib import Path

file = File.from_file(Path('/path/to/report.pdf'))
file.save()

File.from_bytes(filename: str, data: bytes) → File

Creates a File from a byte string.

file = File.from_bytes('document.txt', b'Hello, World!')
file.save()

Instance Methods

to_file(file_or_path: Path | BinaryIO) → None

Writes file data to a path or binary file object.

Raises: ValueError if the path is a directory.

url() → str

Returns a URL for the file from the storage backend.

Raises: StateError if storage_address is not set.

open(mode: str = 'rb') → IO[Any]

Opens a stream for reading the file from storage.

Raises: StateError if storage_address is not set.

read_bytes() → bytes

Reads and returns the full file content as bytes.

set_data(data: bytes | str) → None

Sets file data directly. Only works for files stored in DBStorage.

Raises: ValueError if the file is not stored in a database.


Async Methods

Async Method Description
await file.asave() Save file (inherited from Model)
await file.aurl() Async variant of url()
await file.aopen(mode='rb') Async variant of open()
await file.aread_bytes() Async variant of read_bytes()

Async methods fall back to their sync counterparts if the storage backend does not implement async.