I'm using flask for my application. I'd like to send an image (dynamically generated by PIL) to client without saving on disk.
Any idea how to do this ?
First, you can save the image to a tempfile and remove the local file (if you have one):
from tempfile import NamedTemporaryFile
from shutil import copyfileobj
from os import remove
tempFileObj = NamedTemporaryFile(mode='w+b',suffix='jpg')
pilImage = open('/tmp/myfile.jpg','rb')
copyfileobj(pilImage,tempFileObj)
pilImage.close()
remove('/tmp/myfile.jpg')
tempFileObj.seek(0,0)
Second, set the temp file to the response (as per this stackoverflow question):
from flask import send_file
@app.route('/path')
def view_method():
response = send_file(tempFileObj, as_attachment=True, attachment_filename='myfile.jpg')
return response