Skip to content

Latest commit

History

3 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

Flask-Files

Uploaded files management based on fsspec.

Installation

pip install flask-files

Store uploaded files

Use save_file() to store a Flask file object from request.files. This function returns a File object. Store the value of the File.uri property to later access the file.

fromflaskimportFlaskfromflask_filesimportFiles, save_fileapp=Flask(__name__)
Files(app)
@app.post("/")defindex():
file=save_file(request.files["file"])
print(file.uri)

By default, files are saved to disk prefixed with a UUID.

Validate files from forms

You should validate uploaded files using validate_file(). It will raised a BadRequest error on validation failure.

fromflask_filesimportvalidate_file@app.post("/")defindex():
validate_file(request.files["file"], allowed_exts=[".pdf"], max_size=1024**10)

Use the flask_files.images.IMAGE_EXTS constant for a list of common image extensions.

Serve uploaded files

Use url_for_upload() in combination with the URI stored after saving the file to obtain a public URL for your file.

<imgsrc="{{ url_for_upload(file_or_uri) }}">

You can also re-build a File object from a URI using File.from_uri(uri).

Storage file systems

Flask-Files is built on top of fsspec, allowing it to use any fssspec file system. Compatible file systems must allow write operations.

File systems can allow custom url generation if they provide a url() method (like s3fs).

The default backend can be modified using the FILES_DEFAULT_FILESYSTEM option.

Multiple backends can be used at once by providing the protocol parameter to save_file().

Per filesystem options can be provided in the configuration

FILES_FILESYSTEMS={
"local": {
"subfolders": True
},
"s3": {
"endpoint_url": "https://alternative-service.com"
}
}

You can also use the same filesystem multiple times with different configurations:

FILES_FILESYSTEMS={
"bucket1": {
"protocol": "s3",
"base_path": "bucket1"
},
"bucket2": {
"protocol": "s3",
"base_path": "bucket2"
}
}
save_file(file, protocol="bucket1")
save_file(file, protocol="bucket2")

Using S3

To store files on S3 (or compatible services), setup your AWS credentials as env variables and configure your app as follow:

FILES_DEFAULT_FILESYSTEM="s3"
FILES_BASE_PATH="bucket_name"

Manipulate images

Flask-Files provides functions to manipulate images. They can be chained. The returned image must be stored using save_file().

FunctionDescription
resize_img(file, width, height)Resize an image (only one of width of height is mandatory, ratio is maintained)
create_thumbnail(file, width, height)Create a thumbnail (only one of width of height is mandatory, ratio is maintained)
watermark_img(file, watermark_path, x, y)Add a watermark to an image (x, y are optional, default to lower right corner)
fromflask_files.imagesimportIMAGE_EXTS, create_thumbnail@app.post("/")defindex():
validate_file(request.files["file"], IMAGE_EXTS)
file=save_file(request.files["file"])
thumb=save_file(create_thumbail(file, 100))

File object

The file object is a serializable object that holds information about a file.

It is serializable as string (uri) or JSON.

The stringified representation of a file object is its URL.

Object attributeDescription
pathThe path on the storage
filenameThe filename as it was uploaded
mimetypeMimetype
uuidWhen using uuid prefixes, the uuid prefix
sizeFile size in bytes
url()Generate a url for the file
full_uri()Serialize the object as an URI
to_json()Serializa the object as JSON
open()Open as a file-like object

Configuration

Config KeyExtension argumentDescriptionDefault
FILES_UPLOAD_DIRupload_dirWhere uploaded files are stored on diskuploads
FILES_UPLOAD_URLupload_urlURL from while uploaded files are served/uploads
FILES_DEFAULT_FILESYSTEMdefault_filesystemDefault fsspec file system to useNone (local disk)
FILES_FILESYSTEMSfilesystemsA dict with options for different filesystems

Configuration for file systems:

As default value from app configKey in filesystem configDescriptionDefault
FILES_UUID_PREFIXESuuid_prefixesWhether to prefix filenames with UUIDsTrue
FILES_KEEP_FILENAMEkeep_filenameWhether to keep the original filenameTrue
FILES_SUBFOLDERSsubfoldersWhether to split the first 4 letters are subdirectoriesFalse
FILES_UUID_PREFIX_PATH_SEPARATORuuid_prefix_path_separatorWhether to use the UUID prefix as a folder instead of filename prefixFalse
FILES_BASE_PATHbase_pathBase path for uploaded files, relative to the upload root

About

No description, website, or topics provided.

Resources

Stars

1 star

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages