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}}” />实现图片的显示。