Skip to content

Instantly share code, notes, and snippets.

@Leechael
Created July 24, 2016 08:33
Show Gist options
  • Save Leechael/99383a67f67465cecae53ec24b7fa1df to your computer and use it in GitHub Desktop.
Save Leechael/99383a67f67465cecae53ec24b7fa1df to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from os import environ, path, makedirs
import imghdr
from datetime import datetime, timedelta
from concurrent.futures import ThreadPoolExecutor
from tornado import gen
from tornado.concurrent import run_on_executor
from pilbox.app import ImageHandler as _ImageHandler, Image
class ImageHandler(_ImageHandler):
executor = ThreadPoolExecutor(4)
def initialize(self, path):
self._storage_path = path
self.args = self.request.arguments.copy()
if isinstance(self.args.get("w")):
self.args["w"] = self.args["w"][0]
if isinstance(self.args.get("h")):
self.args["h"] = self.args["h"][0]
if "opt" not in self.args:
self.args["opt"] = 1
if "quality" not in self.args:
self.args["quality"] = 72
def get_argument(self, name, default=None):
return self.args.get(name, default)
def _get_operations(self):
default_operation = "resize"
if "w" not in self.request.arguments and "h" not in self.request.arguments:
default_operation = "noop"
return self.get_argument(
"op", self.settings.get("operation") or default_operation).split(",")
@gen.coroutine
def get(self, slug):
img_path = path.join(self._storage_path, slug)
if not path.exists(img_path):
self.set_status(404)
return
orig_format = imghdr.what(img_path)
with open(img_path, "rb") as srcfile:
outfile, outfile_format = yield self._process_image(srcfile)
now = datetime.now()
expired = now + timedelta(days=10*365)
headers = {
"Content-Type": self._FORMAT_TO_MIME.get(orig_format),
"Expires": expired.strftime("%a, %d %b %Y %H:%M:%S GMT"),
"Last-Modified": now.strftime("%a, %d %b %Y %H:%M:%S GMT"),
}
self._set_headers(headers, outfile_format)
for block in iter(lambda: outfile.read(65536), b""):
self.write(block)
outfile.close()
@run_on_executor
def _process_image(self, buffer):
ops = self._get_operations()
image = Image(buffer)
if "noop" not in ops:
for operation in ops:
if operation == "resize":
self._image_resize(image)
elif operation == "rotate":
self._image_rotate(image)
elif operation == "region":
self._image_region(image)
return (self._image_save(image), image.img.format)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment