]> git.ipfire.org Git - people/shoehn/ipfire.org.git/blob - webapp/handlers_iuse.py
i-use: Fix sending error images.
[people/shoehn/ipfire.org.git] / webapp / handlers_iuse.py
1 #!/usr/bin/python
2
3 import logging
4 import os
5 import random
6 import tornado.web
7
8 from handlers_base import *
9 import backend
10
11 class IUseImage(BaseHandler):
12 def write_error(self, status_code, **kwargs):
13 """
14 Select a random image from the errors directory
15 and return the content.
16 """
17 self.set_header("Content-Type", "image/png")
18
19 template_path = self.application.settings.get("template_path", "")
20 template_path = os.path.join(template_path, "i-use", "errors")
21
22 images = os.listdir(template_path)
23 if images:
24 image = random.choice(images)
25 image = os.path.join(template_path, image)
26
27 imgdata = None
28 with open(image, "rb") as f:
29 imgdata = f.read()
30
31 self.finish(imgdata)
32
33 def get(self, profile_id, image_id):
34 image = None
35 # Try to get the image from memcache. If we have a cache miss we
36 # build a new one.
37 mem_id = "iuse-%s-%s-%s" % (profile_id, image_id, self.locale.code)
38
39 cache = self.get_argument("cache", "true")
40 if cache == "true":
41 image = self.memcached.get(mem_id)
42
43 if image:
44 logging.debug("Got image from cache for profile: %s" % profile_id)
45 else:
46 logging.info("Rendering new image for profile: %s" % profile_id)
47
48 image_cls = self.iuse.get_imagetype(image_id)
49 if not image_cls:
50 raise tornado.web.HTTPError(404, "Image class is unknown: %s" % image_id)
51
52 profile = self.stasy.get_profile(profile_id)
53 if not profile:
54 raise tornado.web.HTTPError(404, "Profile '%s' was not found." % profile_id)
55
56 # Render the image
57 image = image_cls(self.backend, self, profile).to_string()
58
59 # Save the image to the memcache for 15 minutes
60 self.memcached.set(mem_id, image, 15*60)
61
62 self.set_header("Content-Type", "image/png")
63 self.write(image)
64