Flask recommends the Flask-Uploads module for handling uploads. I'd like to reject any file over a certain size. There are a few solutions floating around:
In addition, you can also use patch_request_class to patch your app’s request_class to have a maximum size for uploads.
patch_request_class(app, 32 * 1024 * 1024)
MAX_CONTENT_LENGTH is the correct way to reject file uploads larger than you want,
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024
# save to disk first, then check filesize
request.files['file'].save('/tmp/foo')
size = os.stat('/tmp/foo').st_size
-or-
# save to memory, then check filesize
blob = request.files['file'].read()
size = len(blob)
I don't see MAX_CONTENT_LENGTH
mentioned in the official docs, nor does it even manually check the filesize like the SO post does. Are these two methods ultimately the same, or does there exist a (big/subtle?) difference? Also, does patch_request_class
save the file to disk first to determine total upload size, or does it save to memory?
MAX_CONTENT_LENGTH
is a configuration item for Flask itself, introduced in version 0.6 http://flask.pocoo.org/docs/0.10/patterns/fileuploads/#improving-uploadsAnd from the flask-uploads source: https://bitbucket.org/leafstorm/flask-uploads/src/440e06b851d24811d20f8e06a8eaf5c5bf58c241/flaskext/uploads.py?at=default
So I'd say go with: