I have just begun using the bottle framework and am trying to return an image from a certain Google street view url.
from bottle import run, route, redirect, request, HTTPResponse
import requests
@route('/getimage')
def getimage():
string = 'https://maps.googleapis.com/maps/api/streetview?size=400x400&location=Cleveland, Ohio'
req = requests.get(string, stream=True)
text = req.text
resp = HTTPResponse(body=text,status=400)
resp.set_header('content_type', 'image/jpeg')
return resp
run(host='localhost', port=8080, debug=True)
I don't understand why this is not working - I am attempting to create an HTTPResponse whose body is the text encoding of the image at the given URL; then I am setting the content-type to a jpeg so that it will return as a jpeg, but all I am getting is a message saying that the image cannot be displayed because it has errors. I have tried it on both Firefox and Chrome, and it is not working.
Any help would be much appreciated!
You want r.content
, not r.text
.
From the requests docs:
You can also access the response body as bytes, for non-text requests:
> r.content b'[{"repository":{"open_issues":0,"url":"https://github.com/...
For example, to create an image from binary data returned by a request, you can use the following code:
from PIL import Image from StringIO import StringIO i = Image.open(StringIO(r.content))