Processors
sqlalchemy_file.processors.Processor
Interface that must be implemented by file processors. Can be used to add additional data to the stored file or change it. When file processors are run the file has already been stored.
process(file, upload_storage=None)
abstractmethod
Should be overridden in inherited class Parameters: file: File object, Use file.original_content to access uploaded file upload_storage: pass this to file.store_content() to attach additional files to the original file.
sqlalchemy_file.processors.ThumbnailGenerator
Bases: Processor
Generate thumbnail from original content.
The default thumbnail format and size are PNG@128x128, those can be changed
by giving custom thumbnail_size and thumbnail_format
Note
ThumbnailGenerator will add additional data
to the file object under the key thumbnail.
These data will be store in database.
Properties available in thumbnail attribute
- file_id: This is the ID of the uploaded thumbnail file
- upload_storage: Name of the storage used to save the uploaded file
- path: This is a upload_storage/file_id path which can
be used with :meth:
StorageManager.get_fileto retrieve the thumbnail file - width This is the width of the thumbnail image
- height: This is the height of the thumbnail image
- url: Public url of the uploaded file provided
by libcloud method
Object.get_cdn_url()
Example
class Book(Base):
__tablename__ = "book"
id = Column(Integer, autoincrement=True, primary_key=True)
title = Column(String(100), unique=True)
cover = Column(ImageField(processors=[ThumbnailGenerator()]))
def test_create_image_with_thumbnail(self, fake_image) -> None:
with Session(engine) as session:
from PIL import Image
session.add(Book(title="Pointless Meetings", cover=fake_image))
session.flush()
book = session.execute(
select(Book).where(Book.title == "Pointless Meetings")
).scalar_one()
assert book.cover["thumbnail"] is not None
thumbnail = StorageManager.get_file(book.cover["thumbnail"]["path"])
assert thumbnail is not None
thumbnail = Image.open(thumbnail)
assert max(thumbnail.width, thumbnail.height) == 128
assert book.cover["thumbnail"]["width"] == thumbnail.width
assert book.cover["thumbnail"]["height"] == thumbnail.height