API Reference¶
Core Reference¶
- 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.
- 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.
- name¶
- save(storage: FileStorage, overwrite: bool = False, skip_validation: bool = False) str ¶
Saves the uploaded file and returns an identifier for searching.
- 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.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.
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.
- class flask_uploader.storages.AbstractStorage(filename_strategy: Callable[[FileStorage], str] | None = None)¶
Базовые классы:
object
A file storage that provides basic file operations.
- filename_strategy¶
- 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 theUploader
constructor.- Параметры:
lookup (str) – The unique identifier for the file in the selected storage.
- class flask_uploader.storages.FileSystemStorage(dest: str, filename_strategy: Callable[[FileStorage], str] | None = None)¶
Базовые классы:
AbstractStorage
Local file storage on the HDD.
- dest¶
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.
- 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¶
Utils Reference¶
- flask_uploader.utils.md5file(filename: str) str ¶
Returns the hash sum of the contents of the given file.
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.
- 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.'¶
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.
- methods: ClassVar[Collection[str] | None] = {'POST'}¶
The methods this view is registered for. Uses the same default (
["GET", "HEAD", "OPTIONS"]
) asroute
andadd_url_rule
by default.
- 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 theget_uploader()
method. Used to override the default view./<name>/<path:lookup>
- uses the uploader returned by the static methodget_instance()
. Used as the default view.
- methods: ClassVar[Collection[str] | None] = {'GET'}¶
The methods this view is registered for. Uses the same default (
["GET", "HEAD", "OPTIONS"]
) asroute
andadd_url_rule
by default.
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.
- class flask_uploader.contrib.pymongo.Lookup(value: str)¶
Базовые классы:
str
A search identifier that is both a string and stores a native identifier.
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.
- 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_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.
- is_public¶
- key_prefix¶
- 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.