In my Flask application, a route accepts file uploads via HTTP PUT. Since those files will then be processed by an external tool, I need to save them to disk. Since the files can become larger (a couple hundred MB), I avoid using request.get_data()
but instead use request.stream
to write the incoming data to disk using constant memory:
Right now I do
from tempfile import NamedTemporaryFile
from flask import send_file
# ...
@app.route('/<path>', methods=['PUT'])
def handle_upload(path):
try:
with NamedTemporaryFile(delete=False) as tmpFile:
while True:
chunk = request.stream.read(16384)
if not chunk:
break
tmpFile.write(chunk)
processFile(tmpFile.name) # This calls out to an external tool
return send_file(tmpFile.name)
finally:
os.remove(tmpFile.name)
However, seeing that Flask features convenience methods like send_file
, I wonder: does either Flask or Werkzeug maybe offer a ready-made function to stream the data of a request into a file, something shorter than a hand-written loop? I suspect I may be overlooking something in the API docs.