]>
Commit | Line | Data |
---|---|---|
c37ec602 MT |
1 | #!/usr/bin/python |
2 | ||
d7c4018b | 3 | import datetime |
abc3bb31 | 4 | import logging |
e8478c5e MT |
5 | import os |
6 | import random | |
c37ec602 MT |
7 | import tornado.web |
8 | ||
11347e46 | 9 | from .handlers_base import * |
c37ec602 MT |
10 | |
11 | class IUseImage(BaseHandler): | |
d7c4018b MT |
12 | expires = 3600 * 3 |
13 | ||
30bb04e2 | 14 | def write_error(self, status_code, **kwargs): |
e8478c5e MT |
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 | ||
30bb04e2 | 29 | imgdata = None |
e8478c5e | 30 | with open(image, "rb") as f: |
30bb04e2 MT |
31 | imgdata = f.read() |
32 | ||
33 | self.finish(imgdata) | |
e8478c5e | 34 | |
c37ec602 | 35 | def get(self, profile_id, image_id): |
abc3bb31 | 36 | image = None |
6ec867f2 MT |
37 | |
38 | when = self.get_argument_date("when", None) | |
39 | ||
b3250465 MT |
40 | # Try to get the image from memcache. If we have a cache miss we |
41 | # build a new one. | |
abc3bb31 | 42 | mem_id = "iuse-%s-%s-%s" % (profile_id, image_id, self.locale.code) |
6ec867f2 MT |
43 | if when: |
44 | mem_id += "-%s" % when.isoformat() | |
abc3bb31 MT |
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) | |
c37ec602 | 54 | |
d7bebd28 MT |
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 | ||
b3250465 MT |
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) | |
c37ec602 | 62 | |
b3250465 | 63 | # Render the image |
9068dba1 | 64 | image = image_cls(self.backend, self, profile).to_string() |
c37ec602 | 65 | |
d7c4018b MT |
66 | # Save the image to the memcache |
67 | self.memcached.set(mem_id, image, self.expires) | |
c37ec602 | 68 | |
192f0bdf | 69 | self.set_header("Content-Type", "image/png") |
d7c4018b MT |
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 | ||
b3250465 | 76 | self.write(image) |