I want to response some .png image in my pyramid view. I know the url for that image. I tried urllib, urllib2, requests, but they response object that pyramid view does not understand. My code like this:
def image_handler(request):
url = "http://someurl.com/image.png"
import urllib2
response = urllib2.urlopen(url)
return response
I tried response.read()
too.
Any suggestions? I want that user see image in his web browser
If no renderer
specified in your Pyramid view configuration, your view function is supposed to return a Pyramid Response object, you can't just return random stuff :) Apart from the actual response body, the Response object also encapsulates headers, HTTP response code and other stuff needed to build a correct HTTP response.
urllib2.urlopen returns a "file-like object". pyramid.response has a property called body_file
which can be assigned a file-like object which contents will be sent to the client.
So, I would start with something like this:
import urllib2
def image_handler(request):
url = "http://someurl.com/image.png"
image_file = urllib2.urlopen(url)
request.response.body_file = image_file
request.response.content_type = 'image/png'
return request.response
or, less, efficient, with .read()
def image_handler2(request):
url = "http://someurl.com/image.png"
image_blob = urllib2.urlopen(url).read()
request.response.body = image_blob
request.response.content_type = 'image/png'
return request.response
(both examples untested, treat as pseudocode)