2010-05-15 83 views
1

我试图从我的数据库中获取多个图像路径以显示它们,但它目前不起作用。如何显示多个图像?

以下是我正在使用的是什么:

def get_image(self, userid, id): 
    image = meta.Session.query(Image).filter_by(userid=userid) 
    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 

我收到有关这部分的错误:

image[id].image_path 

我要的是对主塔在1页上显示几个jpg文件。任何想法我怎么能实现这个?

+0

os.path.exists()检查发生得太迟了:如果文件不存在,open()会引发IOError。使用try/except代替。 – 2010-07-07 21:54:36

回答

1

两次使用image.image_path,但在一个地方(你告诉我们,你会犯一个错误),你使用image[id].image_path来代替。你认为id可能是image的适当索引,以及为什么你的代码的不同位置之间的使用差异?

如果你想要一定数量的图像,为什么不使用切片语法?例如。您可以获得前10张图像(确保包含order_by以获得可预测的可重复结果),您可以将filter_by的结果分割为[0:10];第二张10张图片,[10:20];等等。

1

我的猜测是,你假设/希望是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的列表一样。

0

假设“id”包含一个从0到多个图像的数字,您需要先将它从一个字符串转换为一个int,然后才能对数组建立索引。我会做类似

 
def get_image(self, userid, id): 
    images = meta.Session.query(Image).filter_by(userid=userid) 
    try: 
     image = images[int(id)] 
     with open(image.image_path, 'rb') as f: 
      data = f.read() 
    except (IndexError, ValueError, IOError): 
     abort(404) 
    response.content_type = guess_type(image.image_path)[0] or 'application/octet-stream' 
    return data