Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Flask "send_file()" method TypeError

Tags:

python

flask

I'm trying to read an image that the user uploads and then display the image back to them. I want to do this without saving the image file that is uploaded.

I have code like this:

    from flask import Flask, redirect, render_template, request, url_for, send_file
    from PIL import Image, ImageDraw
    from io import BytesIO

    app = Flask(__name__)

        @app.route('/', methods=['GET', 'POST']) 
        def index():
            if request.method == 'POST':    
                 img = Image.open(request.files['file'].stream)
                 byte_io = BytesIO()
                 img.save(byte_io, 'PNG')
                 byte_io.seek(0)
                 return send_file(byte_io, mimetype='image/png')

It produces this error:

TypeError: send_file() got an unexpected keyword argument 'mimetype'

I've tried replacing mimetype with other valid parameters and it will just give the same error but with the name of the new parameter. So I think the problem is with my bytes_io.

UPDATE:

To clarify, by send_file() I'm referring to the built in flask.send_file() method:

like image 491
David Skarbrevik Avatar asked Dec 05 '17 05:12

David Skarbrevik


1 Answers

From flask document

The mimetype guessing requires a filename or an attachment_filename to be provided.

...

  • mimetype – the mimetype of the file if provided. If a file path is given, auto detection happens as fallback, otherwise an error will be raised.

So, you should provide that like this

return send_file(io.BytesIO(obj.logo.read()),
                 attachment_filename='logo.png',
                 mimetype='image/png')

I've updated my answer,
First, below sample code should run normally,

from flask import Flask, request, send_file
app = Flask(__name__)

@app.route('/get_image')
def get_image():
    if request.args.get('type') == '1':
       filename = 'ok.gif'
    else:
       filename = 'error.gif'
    return send_file(filename)


if __name__ == '__main__':
    app.run()

Secondly, if you've still got same error, I think your environment' problem. You can check your python package version using pip freeze.

like image 176
hyun Avatar answered Oct 06 '22 23:10

hyun