import models import os import tornado.ioloop import tornado.web import colour import charts from PIL import Image import io models.db.connect() curpath = os.path.dirname(os.path.abspath(__file__)) tplpath = os.path.join(curpath, "templates"); loader = tornado.template.Loader(tplpath, autoescape=None) config = { "port": 8881, "conn": models.db } emotions = [ e for e in models.Emotion.select().order_by(models.Emotion.name)] class MainHandler(tornado.web.RequestHandler): def get(self): loader.reset() html = loader.load('index.html').generate(host=self.request.host, emotions=emotions, ages=models.getAges(), groups=models.Group.select()) self.write(html) class ThumbHandler(tornado.web.RequestHandler): def get(self, imgId): artwork = models.Artwork.select().where(models.Artwork.id == imgId).get() if artwork is None: self.send_error(404) else: img = Image.open(artwork.filename) img.thumbnail((200,200)) fp = io.BytesIO() img.save(fp, "jpeg") fp.seek(0) self.set_header("Content-Type","image/jpeg") self.set_header("Cache-Control","max-age=2592000, public") self.write(fp.read()) class ColourHandler(tornado.web.RequestHandler): def get(self): req_group = self.get_query_argument("group", default=None) req_age = self.get_query_argument("age", default=None) req_emotion = self.get_query_argument("emotion", default=None) req_work = self.get_query_argument("work", default=None) q = models.Artwork.select().join(models.Group).order_by(models.Group.name) if req_group is not None: group = models.Group.get(models.Group.id == req_group) q = q.where(models.Artwork.group == group) elif req_age is not None: q = q.where(models.Artwork.age == req_age) elif req_emotion is not None: emotion = models.Emotion.get(models.Emotion.id == req_emotion) q = q.where(models.Artwork.emotion == emotion) elif req_work is not None: q = q.where(models.Artwork.id == req_work) images = q svg = colour.getSvgFromDbImages(images) imgHtml = ""; statHtml = ""; self.write("\n".join([svg, imgHtml, statHtml]) ) if __name__ == "__main__": print("Start server", config) app = tornado.web.Application([ (r"/", MainHandler), (r"/colours", ColourHandler), (r"/thumbs/(\d+.jpg)", tornado.web.StaticFileHandler, {'path': './thumbs/'}), (r'/images/(.*)', tornado.web.StaticFileHandler, {'path': './images/'}), ], debug=True) app.listen(config['port']) tornado.ioloop.IOLoop.current().start()