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