API Reference

Core Reference

flask_uploader.init_uploader(app: Flask) None
class flask_uploader.core.UploaderMeta(name: str, bases: tuple[type, ...], d: dict[str, Any])

Базовые классы: type

File uploader metaclass.

Caches instances under the unique name passed in the first argument to the constructor and prevents instantiation of uploaders with the existing name.

get_instance(name: str) Uploader

Returns the uploader instance by unique name.

class flask_uploader.core.Uploader(name: str, storage: AbstractStorage, validators: Sequence[Callable[[FileStorage], None]] | None = None, endpoint: str | None = None, use_auto_route: bool = True)

Базовые классы: object

File uploader with the ability to select different types of storage.

get_url(lookup: str, external: bool = False) str

Returns the URL to the given file.

Параметры:
  • lookup (str) – The unique identifier for the file in the selected storage. Usually this is the path to the file.

  • external (bool) – Generate absolute URL. Default to False.

load(lookup: str) File

Reads and returns a File object for an identifier.

name
remove(lookup: str) None

Deletes a file from storage by unique identifier.

save(storage: FileStorage, overwrite: bool = False, skip_validation: bool = False) str

Saves the uploaded file and returns an identifier for searching.

Параметры:
  • storage (FileStorage) – Object to represent uploaded file.

  • overwrite (bool) – Overwrite existing file. Default to False.

  • skip_validation (bool) – Do not validate the uploaded file. Default to False.

use_auto_route
validate(storage: FileStorage) None

Validates the uploaded file and throws a :py:class`~flask_uploader.exceptions.ValidationError` exception if an error appears.

validators

Exceptions Reference

class flask_uploader.exceptions.UploaderException

Базовые классы: Exception

class flask_uploader.exceptions.FileNotFound

Базовые классы: UploaderException

The file was not found in the storage.

class flask_uploader.exceptions.InvalidLookup

Базовые классы: UploaderException

Incorrect format of a unique identifier used to search for a file in the storage.

class flask_uploader.exceptions.MultipleFilesFound

Базовые классы: UploadNotAllowed

There are multiple files in the storage with the same name, including the prefix, if any.

class flask_uploader.exceptions.PermissionDenied

Базовые классы: UploaderException

The specified action cannot be performed on the storage.

May appear in the following cases:

  • The required directory does not exist.

  • Insufficient rights to perform the action.

  • The third party service responded with an error.

class flask_uploader.exceptions.ValidationError

Базовые классы: UploadNotAllowed

An error when validation of the file.

class flask_uploader.exceptions.UploadNotAllowed

Базовые классы: UploaderException

Any error that prevents the uploaded file from being saved.

Formats Reference

flask_uploader.formats.get_format(path_or_url: str) FileFormat | None

Returns a FileFormat object for the given file or URL.

flask_uploader.formats.guess_type(path_or_url: str, use_external: bool = False) str | None

Returns a mime type for the given file or URL.

Параметры:
  • path_or_url (str) – The path to the file or URL.

  • use_external (bool) – Use the mimetype package.

class flask_uploader.formats.FileFormat(extension, mimetype, comment)

Базовые классы: NamedTuple

comment: str

Alias for field number 2

extension: str

Alias for field number 0

mimetype: str

Alias for field number 1

Storage Reference

class flask_uploader.storages.File(path_or_file: t.Union[str, t.BinaryIO], lookup: t.Optional[str] = None, filename: t.Optional[str] = None, mimetype: t.Optional[str] = None)

Базовые классы: NamedTuple

The result of reading a file from the selected storage.

filename: str | None

Alias for field number 2

lookup: str | None

Alias for field number 1

mimetype: str | None

Alias for field number 3

path_or_file: str | BinaryIO

Alias for field number 0

class flask_uploader.storages.AbstractStorage(filename_strategy: Callable[[FileStorage], str] | None = None)

Базовые классы: object

A file storage that provides basic file operations.

filename_strategy
generate_filename(storage: FileStorage) str

Returns the name of the file to save.

get_url(lookup: str) str | None

Returns the absolute URL for the file.

Used only for external network storage, such as Amazon S3. If you just want to override the default URL, use the endpoint argument of the Uploader constructor.

Параметры:

lookup (str) – The unique identifier for the file in the selected storage.

abstract load(lookup: str) File

Reads and returns a File object for an identifier.

abstract remove(lookup: str) None

Deletes a file from storage by unique identifier.

abstract save(storage: FileStorage, overwrite: bool = False) str

Saves the uploaded file and returns an identifier for searching.

class flask_uploader.storages.FileSystemStorage(dest: str, filename_strategy: Callable[[FileStorage], str] | None = None)

Базовые классы: AbstractStorage

Local file storage on the HDD.

dest
get_root_dir() str

Returns the root directory for saving uploaded files.

load(lookup: str) File

Reads and returns a File object for an identifier.

remove(lookup: str) None

Deletes a file from storage by unique identifier.

save(storage: FileStorage, overwrite: bool = False) str

Saves the uploaded file and returns an identifier for searching.

Strategies Reference

flask_uploader.storages.iter_files(storage: FileSystemStorage) Iterable[File]

Returns an iterator over all files in the given file system storage.

This function cannot be used in a production environment because it returns all files without any filtering. This can lead to memory leaks and freezes.

flask_uploader.storages.TFilenameStrategy

alias of Callable[[FileStorage], str]

class flask_uploader.storages.HashedFilenameStrategy(buffer_size: int = 16384, step: int = 2, max_split: int = 3)

Базовые классы: object

A strategy that generates a name by calculating a hash of the contents of a file and splitting it into the specified number of parts of the specified length.

Solves the problem of storing many files on the hard disk when the number of files in one directory is limited by the OS.

Thanks to the hash and partitioning, files are evenly stored across directories.

buffer_size
max_split
step
class flask_uploader.storages.TimestampStrategy(fmt: str = '%Y-%m-%d-%H-%M-%S', as_int: bool = False)

Базовые классы: object

The strategy uses the current timestamp as the filename.

Can be an integer or a formatted string.

as_int
fmt

Utils Reference

flask_uploader.utils.get_extension(filename: str) str

Returns the file extension.

flask_uploader.utils.md5file(filename: str) str

Returns the hash sum of the contents of the given file.

flask_uploader.utils.md5stream(stream: BinaryIO, buffer_size: int = 16384) str

Returns the hash sum of a binary data stream.

Параметры:
  • stream (bytes) – Binary data stream.

  • buffer_size (int) – The buffer size is the number of bytes held in memory during the hash process. Default to 16Kb.

flask_uploader.utils.split_pairs(hash_sum: str, step: int = 2, max_split: int = 3) list[str]

Splits the hash sum string into parts of the specified length.

Параметры:
  • step (int) – cutting step. Default to 2.

  • max_split (int) – Maximum number of splits to do. Default to 3.

Validators Reference

class flask_uploader.validators.Extension(extensions: set[str] | frozenset[str], message: str | None = None)

Базовые классы: object

The validator checks the file extension.

This is a weak type of validation.

ARCHIVES = frozenset({'7z', 'bz2', 'gz', 'tar', 'tgz', 'txz', 'zip'})
AUDIO = frozenset({'aac', 'flac', 'mp3', 'oga', 'ogg', 'wav', 'wma'})
BOOKS = frozenset({'djv', 'djvu', 'epub', 'fb2', 'mobi', 'pdf'})
DATA = frozenset({'cfg', 'csv', 'ini', 'json', 'plist', 'toml', 'xml', 'yaml', 'yml'})
EBOOKS = frozenset({'epub', 'fb2', 'mobi'})
EDOCUMENTS = frozenset({'djv', 'djvu', 'pdf'})
EXECUTABLES = frozenset({'dll', 'exe', 'so'})
IMAGES = frozenset({'bmp', 'gif', 'jpe', 'jpeg', 'jpg', 'odg', 'png', 'svg', 'webp'})
MS_OFFICE = frozenset({'doc', 'docx', 'ppt', 'pptx', 'xls', 'xlsx'})
OFFICE = frozenset({'abw', 'doc', 'docx', 'dps', 'et', 'gnumeric', 'odc', 'odf', 'odp', 'ods', 'odt', 'ppt', 'pptx', 'rtf', 'wps', 'xls', 'xlsx'})
OPEN_OFFICE = frozenset({'odc', 'odf', 'odp', 'ods', 'odt'})
SCRIPTS = frozenset({'bat', 'js', 'php', 'pl', 'ps1', 'py', 'rb', 'sh'})
SOURCE = frozenset({'D', 'ada', 'asm', 'bas', 'c', 'cbl', 'cob', 'cpp', 'cs', 'cxx', 'f', 'fs', 'go', 'h', 'hpp', 'hs', 'hxx', 'java', 'pas', 'rs', 's'})
TEXT = frozenset({'txt'})
WPS_OFFICE = frozenset({'dps', 'et', 'wps'})
class flask_uploader.validators.FileRequired(message: str | None = None)

Базовые классы: object

The validator checks that the file has been selected and submitted.

class flask_uploader.validators.FileSize(max_size: float | str, min_size: float | str = 0, message: str | None = None)

Базовые классы: object

The validator checks that the file size is not larger than the given.

format_message(message: str, **kwargs: Any) str
to_bytes(size: str) float

Returns the maximum file size in bytes from a human readable string.

to_human(size: float) str

Returns the file size in human readable format.

class flask_uploader.validators.ImageSize(min_width: int = -1, min_height: int = -1, max_width: int = -1, max_height: int = -1, message: str | None = None)

Базовые классы: object

The validator checks the image size in pixels.

EXACT_HEIGHT = 'Image height should be equal %(min_height)dpx.'
EXACT_SIZE = 'Image size should be %(min_width)dx%(min_height)dpx.'
EXACT_WIDTH = 'Image width should be equal %(min_width)dpx.'
HEIGHT_GREATER_EQUAL = 'Image height must be greater than or equal to %(min_height)dpx.'
HEIGHT_LESS_EQUAL = 'Image height must be less than or equal to %(max_height)dpx.'
SIZE_GREATER_EQUAL = 'Image size must be greater than or equal to %(min_width)dx%(min_height)dpx.'
SIZE_LESS_EQUAL = 'Image size must be less than or equal to %(max_width)dx%(max_height)dpx.'
WIDTH_GREATER_EQUAL = 'Image width must be greater than or equal to %(min_width)dpx.'
WIDTH_LESS_EQUAL = 'Image width must be less than or equal to %(max_width)dpx.'
format_message(message: str, **kwargs: Any) str
validate_image(image: Image) None
flask_uploader.validators.TValidator

alias of Callable[[FileStorage], None]

Views Reference

class flask_uploader.views.BaseView(uploader_or_name: str | Uploader | None = None)

Базовые классы: UploaderMixin, MethodView

The base view class for endpoints that use only one uploader.

class flask_uploader.views.DestroyView(uploader_or_name: str | Uploader | None = None)

Базовые классы: BaseView

A view that handles deleting a file by unique lookup.

get_redirect_url() str

Returns the redirect URL after a delete operation.

methods: ClassVar[Collection[str] | None] = {'POST'}

The methods this view is registered for. Uses the same default (["GET", "HEAD", "OPTIONS"]) as route and add_url_rule by default.

post(lookup: str) ResponseReturnValue
class flask_uploader.views.DownloadView(uploader_or_name: str | Uploader | None = None)

Базовые классы: BaseView

The view that handles the file download.

Used with two routes:

  • /<path:lookup> - uses the uploader returned by the get_uploader() method. Used to override the default view.

  • /<name>/<path:lookup> - uses the uploader returned by the static method get_instance(). Used as the default view.

get(lookup: str, name: t.Optional[str] = None) ResponseReturnValue
methods: ClassVar[Collection[str] | None] = {'GET'}

The methods this view is registered for. Uses the same default (["GET", "HEAD", "OPTIONS"]) as route and add_url_rule by default.

send_file(f: File) ResponseReturnValue

Send the contents of a given file to the client.

class flask_uploader.views.UploaderMixin

Базовые классы: object

The mixin adds the uploader_or_name property, whose value is the uploader instance or its unique name, and the get_uploader method, which returns the uploader instance.

get_uploader() Uploader

Returns the uploader instance.

uploader_or_name: str | Uploader | None = None

Contrib Reference

GridFS Reference

flask_uploader.contrib.pymongo.iter_files(storage: GridFSStorage) Iterable[File]

Returns an iterator over all files in the given GridFS storage.

This function cannot be used in a production environment because it returns all files without any filtering. This can lead to memory leaks and freezes.

class flask_uploader.contrib.pymongo.Bucket(db: Database, bucket_name: str = 'fs', chunk_size_bytes: int = 261120, write_concern: WriteConcern | None = None, read_preference: _ServerMode | None = None)

Базовые классы: GridFSBucket

delete_file(filename: str, session: ClientSession | None = None) None

Removes all versions of a file with the given name.

find_last_version(filename: str, session: ClientSession | None = None) GridOut | None

Returns the last uploaded version of the file with the given name or None.

get_last_index(file_pattern: str) int

Returns the last index found for the given filename pattern, otherwise 0.

class flask_uploader.contrib.pymongo.Lookup(value: str)

Базовые классы: str

A search identifier that is both a string and stores a native identifier.

property oid: ObjectId | None
class flask_uploader.contrib.pymongo.GridFSStorage(mongo: PyMongo, collection: str, filename_strategy: Callable[[FileStorage], str] | None = None)

Базовые классы: AbstractStorage

File storage in the MongoDB database.

collection
get_bucket() Bucket

Returns an object for working with GridFS.

load(lookup: str) File

Reads and returns a File object for an identifier.

mongo
remove(lookup: str) None

Deletes a file from storage by unique identifier.

save(storage: FileStorage, overwrite: bool = False) Lookup

Saves the uploaded file and returns an identifier for searching.

Amazon Reference

flask_uploader.contrib.aws.iter_files(storage: S3Storage) Iterable[File]

Returns an iterator over all files in the given S3 storage.

This function cannot be used in a production environment!

flask_uploader.contrib.aws.catch_client_error(exc_type: ~typing.Type[BaseException] = <class 'flask_uploader.exceptions.PermissionDenied'>) Callable[[_F], _F]

The decorator catches all client exceptions and rethrows a new exception with the type specified in the decorator parameter.

class flask_uploader.contrib.aws.AWS(app: Flask | None = None, *, botocore_session: Session | None = None)

Базовые классы: object

app
botocore_session
client(service_name: str, **user_config: Any) BaseClient

Create a low-level service client by name.

Параметры:
  • service_name (str) – The name of a service, e.g. „s3“ or „ec2“.

  • **user_config (dict) – Keyword arguments for the method client().

Результат:

Service client instance.

Тип результата:

botocore.client.BaseClient

get_app() Flask
init_app(app: Flask) None
resource(service_name: str, **user_config: Any) ServiceResource

Create a resource service client by name.

Arguments
service_name (str):

The name of a service, e.g. „s3“ or „ec2“.

**user_config (dict):

Keyword arguments for the method resource().

Результат:

Service resource instance.

Тип результата:

boto3.resources.base.ServiceResource

property session: Session

Returns a session instance that stores configuration state and allows you to create service clients and resources.

teardown(exception: BaseException | None = None) None
class flask_uploader.contrib.aws.S3Storage(s3: S3ServiceResource, bucket_name: str, key_prefix: t.Optional[str] = None, is_public: bool = True, url_expires_in: int = 3600, filename_strategy: t.Optional[TFilenameStrategy] = None)

Базовые классы: AbstractStorage

get_bucket() Bucket

Returns a resource for working with a bucket in S3 object storage.

get_client() S3Client

Returns a low level client instance for working with S3 object storage.

get_resource() S3ServiceResource

Returns a resource instance for working with S3 object storage.

get_url(lookup: str) str

Returns the URL address of an object in S3 object storage.

get_url_pattern() str

Returns the public URL pattern computed programmatically.

is_public
key_prefix
load(lookup: str) File

Reads and returns a File object for an identifier.

remove(lookup: str) None

Deletes a file from storage by unique identifier.

save(storage: FileStorage, overwrite: bool = False) str

Saves the uploaded file and returns an identifier for searching.

url_expires_in

WTForms Reference

flask_uploader.contrib.wtf.file_is_selected(field: FileField) bool

Returns true if the user has uploaded a file, false otherwise.

flask_uploader.contrib.wtf.wrap_validator(cls: _F) _F

Converts the Flask-Uploader validator to a WTForms validator.

class flask_uploader.contrib.wtf.UploadField(*args, **kwargs)

Базовые классы: FileField

A form field for uploading a file and saving it using the uploader.

populate_obj(obj: Any, name: str) None

Saves the uploaded file and populates obj.<name> with the search ID or URL.

Исключение:

flask_uploader.exceptions.UploadNotAllowed – Any error related to the inability to save the file, but not a validation error.

Примечание

This is a destructive operation. If obj.<name> already exists, it will be overridden. Use with caution.

post_validate(form: Form, validation_stopped: bool) None

Runs validators from the uploader.

save() None

Saves the uploaded file.

flask_uploader.contrib.wtf.extension

alias of Extension

flask_uploader.contrib.wtf.file_size

alias of FileSize

flask_uploader.contrib.wtf.image_size

alias of ImageSize