Example #1
0
    def get(self):
        size = self._get_size()
        thumbdir = os.path.join(self.ctx.storage.path, 'thumbnails')
        f = self.ctx.file

        # use a lossless format in doubt
        lossy = f.get_mimetype() == 'image/jpeg'
        thumbext = 'jpg' if lossy else 'png'
        thumbpath = os.path.join(thumbdir, str(size), '%s.%s' % (f.get_hash(), thumbext))
        f.data['thumbnail']['ext'] = thumbext
        f.save()

        mtime = int(os.path.getmtime(f.get_realpath()))
        if not os.path.exists(thumbpath) or mtime != int(os.path.getmtime(thumbpath)):
            if not os.path.isdir(os.path.dirname(thumbpath)):
                os.makedirs(os.path.dirname(thumbpath))
                os.chmod(os.path.dirname(thumbpath), 0770)
            with open(f.get_realpath(), 'rb') as fp:
                img = Image.open(fp)
                img.thumbnail((size, size), Image.BILINEAR)
                with open(thumbpath, 'wb') as tfp:
                    if lossy:
                        img.save(tfp, 'jpeg', quality=95)
                    else:
                        img.save(tfp, 'png')
            os.utime(thumbpath, (mtime, mtime))

        self.ctx.res = FileApp(thumbpath)
        self.ctx.res.cache_control(private=True, max_age=CACHE_CONTROL.ONE_HOUR)
        CONTENT_DISPOSITION.apply(self.ctx.res.headers, inline=True,
            filename="%s_thumb_%s.%s" % (os.path.splitext(f.get_name())[0], size, thumbext))
Example #2
0
 def get(self):
     filename = self.ctx.req.GET.get('file')
     if self.SANITIZE_REGEXP.match(filename):
         realpath = self.find_file(filename)
         if realpath:
             if self.accepts_gzip() and self.compressible(filename):
                 realpath = self.gzip_file(realpath)
             self.ctx.res = FileApp(realpath)
             self.ctx.res.cache_control(public=True, max_age=CACHE_CONTROL.ONE_DAY)
             CONTENT_DISPOSITION.apply(self.ctx.res.headers, inline=True, filename=filename)
             return
         raise HTTPNotFound()
     raise HTTPPreconditionFailed()