我想在我的 Pyramid View 中响应一些 .png 图像。我知道那张图片的网址。 我尝试了 urllib、urllib2、请求,但它们响应 Pyramid View 不理解的对象。 我的代码是这样的:
def image_handler(request):
url = "http://someurl.com/image.png"
import urllib2
response = urllib2.urlopen(url)
return response
我也尝试了 response.read()。
有什么建议吗? 我希望该用户在他的网络浏览器中看到图像
请您参考如下方法:
如果在你的 Pyramid View 配置中没有指定 renderer,你的 View 函数应该返回一个 Pyramid Response 对象,你不能只返回随机的东西 :) 除了实际的响应主体, Response 对象还封装了 header 、HTTP 响应代码和构建正确 HTTP 响应所需的其他内容。
urllib2.urlopen返回一个“类文件对象”。 pyramid.response有一个名为 body_file 的属性,可以为它分配一个类似文件的对象,该对象的内容将被发送到客户端。
所以,我会从这样的事情开始:
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
或者,使用.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
(两个例子都未经测试,视为伪代码)
