Validators
sqlalchemy_file.validators.Validator
Interface that must be implemented by file validators.
File validators get executed before a file is stored on the database using one of the supported fields. Can be used to add additional data to file object or change it.
process(file, attr_key)
abstractmethod
Should be overridden in inherited class.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file
|
File
|
File object |
required |
attr_key
|
str
|
current SQLAlchemy column key. Can be passed to ValidationError |
required |
sqlalchemy_file.validators.SizeValidator
Bases: Validator
Validate file maximum size.
Attributes:
| Name | Type | Description | ||||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
max_size |
The size of the underlying file must be below this file size in order to be valid. The size of the file can be given in one of the following formats:
For more information, view Wikipedia: Binary prefix |
Example
Raises:
| Type | Description |
|---|---|
SizeValidationError
|
When file |
sqlalchemy_file.validators.ContentTypeValidator
Bases: Validator
Validate file mimetype
Attributes:
allowed_content_types: If set, file content_type
must be one of the provided list.
Example
Raises:
| Type | Description |
|---|---|
ContentTypeValidationError
|
When file |
sqlalchemy_file.validators.ImageValidator
Bases: ContentTypeValidator
Default Validator for ImageField.
Attributes:
| Name | Type | Description |
|---|---|---|
min_wh |
Minimum allowed dimension (w, h). |
|
max_wh |
Maximum allowed dimension (w, h). |
|
allowed_content_types |
An iterable whose items are
allowed content types. Default is |
|
min_aspect_ratio |
Minimum allowed image aspect ratio. |
|
max_aspect_ratio |
Maximum allowed image aspect ratio. |
Example
class Book(Base):
__tablename__ = "book"
id = Column(Integer, autoincrement=True, primary_key=True)
title = Column(String(100), unique=True)
cover = Column(
ImageField(
image_validator=ImageValidator(
allowed_content_types=["image/x-icon", "image/tiff", "image/jpeg"],
min_wh=(200, 200),
max_wh=(400, 400),
min_aspect_ratio=1,
max_aspect_ratio=16/9,
)
)
)
Raises:
| Type | Description |
|---|---|
ContentTypeValidationError
|
When file |
InvalidImageError
|
When file is not a valid image |
DimensionValidationError
|
When image width and height constraints fail. |
Will add width and height properties to the file object