edA-qa mort-ora-y
edA-qa mort-ora-y

Reputation: 31871

requests get image, return via flask

I am trying to get an image via requests and return that image from a flask application. I've not having any luck reading the binary data from the request, my resulting response is always 0 bytes.

@app.route('/image')
def get_image:
    zs = requests.Session()
    r = zs.get( 'url_that_loads_a_png' )
    fr = make_response( r.raw.read() )
    fr.headers['Content-Type'] = r.headers['Content-Type']
    return fr

I assume my make_response( r.raw.read() ) is somehow incorrect, but I'm not sure what it should be. I've searched for other answers and based the above on them, but they are always slightly different (usually involving a file).

Upvotes: 4

Views: 1627

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1122082

You are not making a streaming request, so the raw socket has already been read from. Just use r.content instead:

fr = make_response(r.content)

The raw socket can only be read from still if you used stream=True when creating the request:

r = zs.get('url_that_loads_a_png', stream=True)

but since you are reading the whole response into memory anyway there is not much point in doing so here.

Upvotes: 6

Related Questions