rubayeet
rubayeet

Reputation: 9400

Python Flask - making ALL file uploads go to tmp directory

According to the docs, Flask stores the uploaded file in-memory if the file is 'reasonably small' (no upper limit mentioned) and otherwise in temporary location as returned by tempfile.gettempdir().

How can I make it store ALL files to the temporary directory?

Upvotes: 3

Views: 5678

Answers (1)

kmonsoor
kmonsoor

Reputation: 8119

According to a Flask doc, handling of uploading files is actually handled by its underlying werkzeug WSGI utility library.

As per werkzeug's documentation the lower-limit for getting file's temp location, as you mentioned as "reasonably small", is 500KB.

The default implementation returns a temporary file if the total content length is higher than 500KB. Because many browsers do not provide a content length for the files only the total content length matters.

Let's look into the upper limit. As per aforementioned Flask doc,

By default Flask will happily accept file uploads to an unlimited amount of memory,but you can limit that by setting the MAX_CONTENT_LENGTH config key.

For example, this code fragment

from flask import Flask, Request
app = Flask(__name__)
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024

will limited the maximum allowed payload to 16 megabytes. If a larger file is transmitted, Flask will raise an werkzeug.exceptions.RequestEntityTooLarge exception.

Now, answering your core question

How can I make it store ALL files to the temporary directory?

You can do that by overriding default_stream_factory() function to this:

def default_stream_factory(total_content_length, filename, content_type, content_length=None):
    """The stream factory that is used per default."""
    # if total_content_length > 1024 * 500:
    #    return TemporaryFile('wb+')
    # return BytesIO()
    return TemporaryFile('wb+')

Upvotes: 7

Related Questions