Google App Engine显示数据库中的图片
GAE目前还不允许用户操作文件系统,上传的图片只能通过数据库存取。以下的代码实现了shop表中logo图片的动态显示:
class showShopLogo(webapp.RequestHandler): def get(self): shopid = self.request.get('sid') shop = Shop.get_by_id(int(shopid)) if (shop and shop.logo): img = images.Image(shop.logo) img.resize(width=128, height=128) tumbimg = img.execute_transforms(output_encoding=images.PNG) self.response.headers['Content-Type'] = 'image/png' self.response.out.write(tumbimg) else: self.redirect('/images/nologo.png')
定义处理路径:
application = webapp.WSGIApplication(
[ ...
('/shop/logo', showShopLogo),
( ...)
], debug=True)
wsgiref.handlers.CGIHandler().run(application)
我们可以通过http://example.com/shop/logo?sid=5这样的格式访问图片,在模板文件中,用<img src=”/shop/logo?sid={{shop.key.id}}” />实现图片的显示。

可否請問GAE詳細存圖檔的方法 我db不知道有什麼形式可以用來儲存圖檔的
Hi, passerby
在您的model中,需要把存放图像的字段,如logo,定义成:
template看起来象下面的样子:
<form id="myShopForm" action="" method="post" enctype="multipart/form-data"> ... Logo: (The picture will be resized to 128 X 128px)<br /> <input type="file" name="logo" /> ...最后是存储过程:
def post(self): ... logo = images.resize(self.request.get('logo'),128,128) logo = db.Blob(logo) ... shop.put()您也可以从app engine文档Using the Images API获得帮助,如果需要从其他网站链接的图片文件存储到数据库,您可以查阅Serving Dynamic Images with Google App Engine这一篇。
說的很詳細 感謝您