Exemplo n.º 1
0
    def get(self,
            flip_horizontal,
            width,
            flip_vertical,
            height,
            halign,
            valign,
            url):

        url = self.validate_url(url)

        width = width and int(width) or 0
        height = height and int(height) or 0

        if width > MAX_WIDTH:
            width = MAX_WIDTH
        if height > MAX_HEIGHT:
            height = MAX_HEIGHT

        if not halign:
            halign = "center"
        if not valign:
            valign = "middle"

        key = "%d_%d_%s_%s_%s" % (
                width,
                height,
                halign,
                valign,
                url
        )

        extension = splitext(url)[-1]
        image_format = extension in ('.jpg', '.jpeg') and JPEG or PNG

        data = memcache.get(key)

        self.response.headers['Cache-Key'] = key
        if data is not None:
            results = data
            self.response.headers['Cache-Hit'] = 'True'
        else:
            query = "SELECT * FROM Picture WHERE url = :1 LIMIT 1"
            pictures = db.GqlQuery(query, url).fetch(1)

            try:
                if len(pictures) > 0: 
                    picture = pictures[0]
                    if picture.is_expired():
                        img = picture.fetch_image()
                        try:
                            picture.put()
                        except RequestTooLargeError:
                            picture.rebalance_picture_size(self.transform)
                            picture.put()
                    else:
                        img = Image(picture.picture)
                else:
                    picture = Picture()
                    picture.url = url
                    img = picture.fetch_image()
                    try:
                        picture.put()
                    except RequestTooLargeError:
                        picture.rebalance_picture_size(self.transform)
                        picture.put()
            except ImageNotFoundError:
                self._error(404, 'Your image source is not found!')
                return

            results = self.transform(img, width, flip_horizontal, height, flip_vertical, image_format, halign, valign)

            memcache.set(key=key,
                     value=results,
                     time=EXPIRATION) # ONE MONTH

            self.response.headers['Cache-Hit'] = 'False'

        self.response.headers['Content-Type'] = image_format == JPEG and 'image/jpeg' or 'image/png'
        self.response.out.write(results)