我的猜测是,你假设/希望是filter_by查询的结果包含一个字典映射检索到他们的ID的图像。相反,它拥有一个查询对象,该对象表示在被强制访问像Alex提到的切片表达式或迭代操作时返回可迭代结果集的承诺。
这可能不是解决这个问题的最好办法,但我的猜测是,修改代码看起来像这样可能会完成你想要的:
def get_image(self, userid, id):
image = meta.Session.query(Image).filter_by(userid=userid)
image = dict((img.id, img) for img in image)
permanent_file = open(image[id].image_path, 'rb')
if not os.path.exists(image.image_path):
return 'No such file'
data = permanent_file.read()
permanent_file.close()
response.content_type = guess_type(image.image_path)[0] or 'text/plain'
return data
更明智的方法是什么像这样:
def get_image(self, userid, id):
image = meta.Session.query(Image).filter_by(userid=userid).filter_by(id=id).first()
# TODO: Handle the case when image is None
permanent_file = open(image[id].image_path, 'rb')
if not os.path.exists(image.image_path):
return 'No such file'
data = permanent_file.read()
permanent_file.close()
response.content_type = guess_type(image.image_path)[0] or 'text/plain'
return data
当然你要假定图像存在匹配查询,它可能没有,所以你应该有一些错误处理为,我离开了TODO注释。
当然,这些更改中的任何一项都只会返回单个图像的数据。如果你想要多个图像,你将不得不为每个图像调用一次该函数,可能在请求处理程序中为某种图像视图调用。
如果你确实想要一次返回多个图像的原始图像数据,那么Alex的建议是使用切片来取回例如每次从数据库中记录10条记录可能是最好的方法,但是您必须修改剩余的代码以遍历N张图像列表,并从文件系统中检索每个数据并返回一些内容就像原始图像数据blob的列表一样。
os.path.exists()检查发生得太迟了:如果文件不存在,open()会引发IOError。使用try/except代替。 – 2010-07-07 21:54:36