Python Flask - making ALL file uploads go to tmp directory
Question: According to the
[docs](http://flask.pocoo.org/docs/0.10/patterns/fileuploads/#improving-
uploads), 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?


Answer: According to a [`Flask`
doc](https://github.com/mitsuhiko/flask/blob/master/docs/patterns/fileuploads.rst#uploading-
files), handling of uploading files is actually handled by its underlying
[werkzeug](http://werkzeug.pocoo.org/) WSGI utility library.

As per [werkzeug's
documentation](http://werkzeug.pocoo.org/docs/0.11/wrappers/#werkzeug.wrappers.BaseRequest._get_file_stream)
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](https://github.com/mitsuhiko/flask/blob/master/docs/patterns/fileuploads.rst#uploading-
files),

> 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()`](https://github.com/mitsuhiko/werkzeug/blob/master/werkzeug/formparser.py#L38)
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+')
    

