API Documentation

Resizing

class flask_resize.resizing.Resize(app=None)

Used for initializing the configuration needed for the Resizer instance, and for the jinja filter to work in the flask app.

Parameters:app (Any[flask.Flask, None]) – A Flask app can be passed in immediately if not using the app factory pattern.
init_app(app)

Initialize Flask-Resize

Parameters:app (flask.Flask) – The Flask app to configure.
Raises:RuntimeError – A setting wasn’t specified, or was invalid.
class flask_resize.resizing.Resizer(storage_backend, cache_store, base_url, name_hashing_method='sha1', target_directory='resized-images', raise_on_generate_in_progress=False, noop=False)

Factory for creating the resize function

__call__(image_url, dimensions=None, format=None, quality=80, fill=False, bgcolor=None, upscale=True, progressive=True, placeholder=False)

Method for resizing, converting and caching images

Parameters:
  • image_url (str) – URL for the image to resize. A URL relative to base_url
  • dimensions (str, Sequence[int, int]) – Width and height to use when generating the new image. Uses the format of parse_dimensions(). No resizing is done if None is passed in.
  • format (Optional[str]) – Format to convert into. Defaults to using the same format as the original image. An exception to this default is when the source image is of type SVG/SVGZ, then PNG is used as default.
  • quality (int) – Quality of the output image, if the format is JPEG. Defaults to 80.
  • fill (bool) – Fill the entire width and height that was specified if True, otherwise keep the original image dimensions. Defaults to False.
  • bgcolor (Optional[str]) – If specified this color will be used as background.
  • upscale (bool) – Whether or not to allow the image to become bigger than the original if the request width and/or height is bigger than its dimensions. Defaults to True.
  • progressive (bool) – Whether to use progressive encoding or not when JPEG is the output format. Defaults to True.
  • placeholder (bool) – Whether to show a placeholder if the specified image_url couldn’t be found.
Raises:
  • exc.EmptyImagePathError – If an empty image path was received.
  • exc.ImageNotFoundError – If the image could not be found.
  • exc.MissingDimensionsError – If fill argument was True, but width or height was not passed.
Returns:

URL to the generated and cached image.

Return type:

str

Usage:

Generate an image from the supplied image URL that will fit within an area of 600px width and 400px height:

resize('somedir/kittens.png', '600x400')

Resize and crop so that the image will fill the entire area:

resize('somedir/kittens.png', '300x300', fill=1)

Convert to JPG:

resize('somedir/kittens.png', '300x300', format='jpg')
flask_resize.resizing.create_placeholder_image(width=None, height=None, message=None)

Create a placeholder image that specified its width and height, and an optional text.

Parameters:
  • width (Optional[str]) – Width to use for the image. Will use height if not provided.
  • height (Optional[str]) – Height to use for the image. Will use width if not provided.
  • message (Optional[str]) – Text to add to the center of the placeholder image.
Raises:

exc.MissingDimensionsError – If neither width nor height are provided.

Returns:

The placeholder image.

Return type:

PIL.Image

flask_resize.resizing.format_to_ext(format)

Return the file extension to use for format

flask_resize.resizing.image_data(img, format, **save_options)

Save a PIL Image instance and return its byte contents

flask_resize.resizing.make_opaque(img, bgcolor)

Apply a background color to image

Parameters:
  • img (PIL.Image) – Image to alter.
  • bgcolor (str) – A parse_rgb() parseable value to use as background color.
Returns:

A new image with the background color applied.

Return type:

PIL.Image

flask_resize.resizing.make_resizer(config)

Resizer instance factory

Storage

class flask_resize.storage.FileStorage(base_path)

Local file based storage

Note that to follow the same convention as for S3Storage, all methods’ passed in and extracted paths must use forward slash as path separator. the path separator. The only exception is the base_path passed in to the constructor.

Parameters:base_path (str) – The directory where files will be read from and written to. Expected to use the local OS’s path separator.
delete(key)

Delete file at specified key

Parameters:key (str) – The key / relative file path to delete
delete_tree(subdir)

Recursively deletes all regular files in specified sub-directory

Parameters:subdir (str) – The subdirectory to delete files in
Returns:Yields deleted subdirectory’s filenames
Return type:Generator[str, str, None]
exists(key)

Check if the key exists in the backend

Parameters:key (str) – The key / relative file path to check
Returns:Whether the file exists or not
Return type:bool
get(key)

Get binary file data for specified key

Parameters:key (str) – The key / relative file path to get data for
Returns:The file’s binary data
Return type:bytes
list_tree(subdir)

Recursively yields all regular files’ names in a sub-directory of the storage backend.

Keys/filenames are returned self.base_path-relative, and uses forward slash as a path separator, regardless of OS.

Parameters:subdir (str) – The subdirectory to list paths for
Returns:Yields subdirectory’s filenames
Return type:Generator[str, str, None]
save(key, bdata)

Store binary file data at specified key

Parameters:
  • key (str) – The key / relative file path to store data at
  • bdata (bytes) – The file data
class flask_resize.storage.S3Storage(bucket, access_key=None, secret_key=None, region_name=None, file_acl='public-read')

Amazon Web Services S3 based storage

Parameters:
  • bucket (str) – Bucket name
  • access_key (Any[str, None]) – The access key. Defaults to reading from the local AWS config.
  • secret_key (Any[str, None]) – The secret access key. Defaults to reading from the local AWS config.
  • region_name (Any[str, None]) – The name of the bucket’s region. Defaults to reading from the local AWS config.
  • file_acl (str) – The ACL to set on uploaded images. Defaults to “public-read”
base_url

The base URL for the storage’s bucket

Returns:The URL
Return type:str
delete(relative_path)

Delete file at specified key

Parameters:key (str) – The key to delete
delete_tree(subdir)

Recursively deletes all keys in specified sub-directory (prefix)

Parameters:subdir (str) – The subdirectory to delete keys in
Returns:Yields subdirectory’s deleted keys
Return type:Generator[str, str, None]
exists(relative_path)

Check if the key exists in the backend

Parameters:key (str) – The key to check
Returns:Whether the key exists or not
Return type:bool
get(relative_path)

Get binary file data for specified key

Parameters:key (str) – The key to get data for
Returns:The file’s binary data
Return type:bytes
list_tree(subdir)

Recursively yields all keys in a sub-directory of the storage backend

Parameters:subdir (str) – The subdirectory to list keys for
Returns:Yields subdirectory’s keys
Return type:Generator[str, str, None]
save(relative_path, bdata)

Store binary file data at specified key

Parameters:
  • key (str) – The key to store data at
  • bdata (bytes) – The file data
class flask_resize.storage.Storage(*args, **kwargs)

Storage backend base class

flask_resize.storage.make(config)

Generate storage backend from supplied config

Parameters:config (dict) – The config to extract settings from
Returns:A Storage sub-class, based on the RESIZE_STORAGE_BACKEND value.
Return type:Any[FileStorage, S3Storage]
Raises:RuntimeError – If another RESIZE_STORAGE_BACKEND value was set

Cache

class flask_resize.cache.Cache

Cache base class

class flask_resize.cache.NoopCache

No-op cache, just to get the same API regardless of whether cache is used or not.

add(unique_key)

Add key to cache

Parameters:unique_key (str) – Add this key to the cache
Returns:Whether key was added or not
Return type:bool
all()

List all keys in cache

Returns:All the keys in the set, as a list
Return type:List[str]
clear()

Remove all keys from cache

Returns:Whether any keys were removed or not
Return type:bool
exists(unique_key)

Check if key exists in cache

Parameters:unique_key (str) – Unique key to check for
Returns:Whether key exist in cache or not
Return type:bool
remove(unique_key)

Remove key from cache

Parameters:unique_key (str) – Remove this key from the cache
Returns:Whether key was removed or not
Return type:bool
transaction(unique_key, ttl=600)

No-op context-manager for transactions. Always yields True.

class flask_resize.cache.RedisCache(host='localhost', port=6379, db=0, password=None, key='flask-resize')

A Redis-based cache that works with a single set-type key

Basically just useful for checking whether an expected value in the set already exists (which is exactly what’s needed in Flask-Resize)

add(unique_key)

Add key to cache

Parameters:unique_key (str) – Add this key to the cache
Returns:Whether key was added or not
Return type:bool
all()

List all keys in cache

Returns:All the keys in the set, as a list
Return type:List[str]
clear()

Remove all keys from cache

Returns:Whether any keys were removed or not
Return type:bool
exists(unique_key)

Check if key exists in cache

Parameters:unique_key (str) – Unique key to check for
Returns:Whether key exist in cache or not
Return type:bool
remove(unique_key)

Remove key from cache

Parameters:unique_key (str) – Remove this key from the cache
Returns:Whether key was removed or not
Return type:bool
transaction(unique_key, ttl=600)

Context-manager to use when it’s important that no one else handles unique_key at the same time (for example when saving data to a storage backend).

Parameters:
  • unique_key (str) – The unique key to ensure atomicity for
  • ttl (int) – Time before the transaction is deemed irrelevant and discarded from cache. Is only relevant if the host forcefully restarts.
flask_resize.cache.make(config)

Generate cache store from supplied config

Parameters:config (dict) – The config to extract settings from
Returns:A Cache sub-class, based on the RESIZE_CACHE_STORE value.
Return type:Any[RedisCache, NoopCache]
Raises:RuntimeError – If another RESIZE_CACHE_STORE value was set

Configuration

class flask_resize.configuration.Config(**config)

The main configuration entry point

classmethod from_dict(dct, default_overrides=None)

Turns a dictionary with RESIZE_ prefix config options into lower-case keys on this object.

Parameters:
  • dct (dict) – The dictionary to get explicitly set values from
  • default_overrides (Any[dict,None]) – A dictionary with default overrides, where all declared keys’ values will be used as defaults instead of the “app default”, in case a setting wasn’t explicitly added to config.

Constants

flask_resize.constants.DEFAULT_NAME_HASHING_METHOD = 'sha1'

Default filename hashing method for generated images

flask_resize.constants.DEFAULT_REDIS_KEY = 'flask-resize'

Default key to store redis cache as

flask_resize.constants.DEFAULT_TARGET_DIRECTORY = 'resized-images'

Default target directory for generated images

flask_resize.constants.JPEG = 'JPEG'

JPEG format

flask_resize.constants.PNG = 'PNG'

PNG format

flask_resize.constants.SUPPORTED_OUTPUT_FILE_FORMATS = ('JPEG', 'PNG')

Image formats that can be generated

flask_resize.constants.SVG = 'SVG'

SVG format

Exceptions

exception flask_resize.exc.Boto3ImportError

Raised when S3 is configured, but the boto3 library is not installed.

exception flask_resize.exc.CacheMiss

Raised when a cached image path could not be found

exception flask_resize.exc.CairoSVGImportError

Raised when an SVG input file is encountered but CairoSVG is not installed.

exception flask_resize.exc.EmptyImagePathError

Raised if an empty image path was encountered.

exception flask_resize.exc.GenerateInProgress

The image is currently being generated

exception flask_resize.exc.ImageNotFoundError

Raised if the image could not be fetched from storage.

exception flask_resize.exc.InvalidDimensionsError

Raised when a dimension string/tuple is improperly specified.

exception flask_resize.exc.InvalidResizeSettingError

Raised when a resize argument such as if width was invalid.

exception flask_resize.exc.MissingDimensionsError

Raised when width and/or height is missing.

exception flask_resize.exc.RedisImportError

Raised when Redis cache is configured, but the redis library is not installed.

exception flask_resize.exc.UnsupportedImageFormatError

Raised when an unsupported output image format is encountered.