riede
riede

Reputation: 58

Send an image with flask by using urllib2

I'm new to Flask and I want to send an image to a client that was previously received from a external server with urllib2. Here is my example code for sending the google logo to the client:

import urllib2
from flask import Flask, send_file

app = Flask(__name__)

@app.route('/getTestImage')
def getTestImage():

    url = "https://www.google.de/images/srpr/logo11w.png"

    response = urllib2.urlopen(url)
    img = response.read()
    response.close()

    return img

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

When I open 127.0.0.1:5000/getTestImage with a browser ( e.g. Firefox) I just get binary code. How do I send the png file so that the browser display the image? I found send_file from Flask but I don't realy know how to use the function with the received image data from urllib2.

Edit: I figured it out. Simply return Response(img, mimetype="image/png").

Upvotes: 0

Views: 823

Answers (1)

davidism
davidism

Reputation: 127180

You see binary data because you're returning the image data directly. Flask wraps text returned from a view in its default Response object, which sets the mimetype to text/plain. Since you're not returning plain text data, you need to create a response that describes the correct mimetype.

return app.response_class(img, mimetype='image/png')

Upvotes: 1

Related Questions