如何显示多张图片?
我正在尝试从数据库中获取多个图片的路径,以便显示它们,但现在这个功能不太好使。
这是我现在用的代码:
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
我想让Pylons在一页上显示多个jpg文件。有没有什么办法可以做到这一点?
3 个回答
假设“id”是一个从0开始到图片总数的数字,你需要把它从字符串转换成整数,这样才能用它来查找数组中的元素。我会这样做:
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
你在代码中两次使用了 image.image_path
,但在一个地方(你提到的出错的地方)却用了 image[id].image_path
。那这个 id
是什么呢?你觉得它能正确地索引到 image
,为什么在代码的不同地方使用方式会不一样呢?
如果你想要获取一定数量的图片,为什么不使用切片语法呢?比如,你可以通过 [0:10]
来获取前10张图片(记得加上 order_by
,这样结果会更稳定可重复),第二组10张图片用 [10:20]
,依此类推。
我猜你之前的想法是希望通过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张图片的列表,从文件系统中获取每张图片的数据,并返回类似原始图片数据块的列表。