API Reference¶
Core Reference¶
- class flask_uploader.core.UploaderMeta(name: str, bases: tuple[type, ...], d: dict[str, Any])¶
Базовые классы:
typeFile 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: Optional[Sequence[Callable[[FileStorage], None]]] = None, endpoint: Optional[str] = None, use_auto_route: bool = True)¶
Базовые классы:
objectFile 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¶
Базовые классы:
UploaderExceptionThe file was not found in the storage.
- class flask_uploader.exceptions.InvalidLookup¶
Базовые классы:
UploaderExceptionIncorrect format of a unique identifier used to search for a file in the storage.
- class flask_uploader.exceptions.MultipleFilesFound¶
Базовые классы:
UploadNotAllowedThere are multiple files in the storage with the same name, including the prefix, if any.
- class flask_uploader.exceptions.PermissionDenied¶
Базовые классы:
UploaderExceptionThe 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¶
Базовые классы:
UploadNotAllowedAn error when validation of the file.
- class flask_uploader.exceptions.UploadNotAllowed¶
Базовые классы:
UploaderExceptionAny error that prevents the uploaded file from being saved.
Formats Reference¶
- flask_uploader.formats.get_format(path_or_url: str) Optional[FileFormat]¶
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)¶
Базовые классы:
NamedTupleThe result of reading a file from the selected storage.
- class flask_uploader.storages.AbstractStorage(filename_strategy: Optional[Callable[[FileStorage], str]] = None)¶
Базовые классы:
objectA 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) Optional[str]¶
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
endpointargument of theUploaderconstructor.- Параметры
lookup (str) – The unique identifier for the file in the selected storage.
- 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: Optional[Callable[[FileStorage], str]] = None)¶
Базовые классы:
AbstractStorageLocal file storage on the HDD.
- dest¶
- 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)¶
Базовые классы:
objectA 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: Union[set[str], frozenset[str]], message: Optional[str] = None)¶
Базовые классы:
objectThe 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: Optional[str] = None)¶
Базовые классы:
objectThe validator checks that the file has been selected and submitted.
- class flask_uploader.validators.FileSize(max_size: Union[float, str], min_size: Union[float, str] = 0, message: Optional[str] = None)¶
Базовые классы:
objectThe 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: Optional[str] = None)¶
Базовые классы:
objectThe 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.'¶
- flask_uploader.validators.TValidator¶
alias of
Callable[[FileStorage],None]
Views Reference¶
- class flask_uploader.views.BaseView(uploader_or_name: Optional[Union[str, Uploader]] = None)¶
Базовые классы:
UploaderMixin,MethodViewThe base view class for endpoints that use only one uploader.
- class flask_uploader.views.DestroyView(uploader_or_name: Optional[Union[str, Uploader]] = None)¶
Базовые классы:
BaseViewA view that handles deleting a file by unique lookup.
- class flask_uploader.views.DownloadView(uploader_or_name: Optional[Union[str, Uploader]] = None)¶
Базовые классы:
BaseViewThe 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.
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: Optional[WriteConcern] = None, read_preference: Optional[_ServerMode] = None)¶
Базовые классы:
GridFSBucket- delete_file(filename: str, session: Optional[ClientSession] = None) None¶
Removes all versions of a file with the given name.
- class flask_uploader.contrib.pymongo.Lookup(value: str)¶
Базовые классы:
strA search identifier that is both a string and stores a native identifier.
- class flask_uploader.contrib.pymongo.GridFSStorage(mongo: PyMongo, collection: str, filename_strategy: Optional[Callable[[FileStorage], str]] = None)¶
Базовые классы:
AbstractStorageFile storage in the MongoDB database.
- collection¶
- mongo¶
- 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: Optional[Flask] = None, *, botocore_session: Optional[Session] = 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: Optional[BaseException] = 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)¶
Базовые классы:
FileFieldA 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.