]> git.ipfire.org Git - ipfire.org.git/blob - src/web/handlers_iuse.py
Run 2to3 to move to Python 3
[ipfire.org.git] / src / web / handlers_iuse.py
1 #!/usr/bin/python
2
3 import datetime
4 import logging
5 import os
6 import random
7 import tornado.web
8
9 from .handlers_base import *
10
11 class IUseImage(BaseHandler):
12 expires = 3600 * 3
13
14 def write_error(self, status_code, **kwargs):
15 """
16 Select a random image from the errors directory
17 and return the content.
18 """
19 self.set_header("Content-Type", "image/png")
20
21 template_path = self.application.settings.get("template_path", "")
22 template_path = os.path.join(template_path, "i-use", "errors")
23
24 images = os.listdir(template_path)
25 if images:
26 image = random.choice(images)
27 image = os.path.join(template_path, image)
28
29 imgdata = None
30 with open(image, "rb") as f:
31 imgdata = f.read()
32
33 self.finish(imgdata)
34
35 def get(self, profile_id, image_id):
36 image = None
37
38 when = self.get_argument_date("when", None)
39
40 # Try to get the image from memcache. If we have a cache miss we
41 # build a new one.
42 mem_id = "iuse-%s-%s-%s" % (profile_id, image_id, self.locale.code)
43 if when:
44 mem_id += "-%s" % when.isoformat()
45
46 cache = self.get_argument("cache", "true")
47 if cache == "true":
48 image = self.memcached.get(mem_id)
49
50 if image:
51 logging.debug("Got image from cache for profile: %s" % profile_id)
52 else:
53 logging.info("Rendering new image for profile: %s" % profile_id)
54
55 profile = self.fireinfo.get_profile_with_data(profile_id, when=when)
56 if not profile:
57 raise tornado.web.HTTPError(404, "Profile '%s' was not found." % profile_id)
58
59 image_cls = self.iuse.get_imagetype(image_id)
60 if not image_cls:
61 raise tornado.web.HTTPError(404, "Image class is unknown: %s" % image_id)
62
63 # Render the image
64 image = image_cls(self.backend, self, profile).to_string()
65
66 # Save the image to the memcache
67 self.memcached.set(mem_id, image, self.expires)
68
69 self.set_header("Content-Type", "image/png")
70
71 # Set expiry headers
72 self.set_header("Expires",
73 datetime.datetime.utcnow() + datetime.timedelta(seconds=self.expires))
74 self.set_header("Cache-Control", "public,max-age=%d" % self.expires)
75
76 self.write(image)