38 Scale value about center by zoom. |
37 Scale value about center by zoom. |
39 """ |
38 """ |
40 |
39 |
41 return scale(val - dim / 2, zoom) |
40 return scale(val - dim / 2, zoom) |
42 |
41 |
43 class Application (object): |
42 class TileApplication (BaseApplication): |
44 def __init__ (self, image_root): |
43 def __init__ (self, **opts): |
45 if not os.path.isdir(image_root) : |
44 BaseApplication.__init__(self, **opts) |
46 raise Exception("Given image_root does not exist: {image_root}".format(image_root=image_root)) |
|
47 |
|
48 self.image_root = os.path.abspath(image_root) |
|
49 |
|
50 self.image_cache = { } |
|
51 |
|
52 def lookup_image (self, url): |
|
53 """ |
|
54 Lookup image by request path. |
|
55 |
|
56 Returns image_name, image_path. |
|
57 """ |
|
58 |
|
59 if not os.path.isdir(self.image_root): |
|
60 raise exceptions.InternalServerError("Server image_root has gone missing") |
|
61 |
|
62 # path to image |
|
63 name = url.lstrip('/') |
|
64 |
45 |
65 # build absolute path |
|
66 path = os.path.abspath(os.path.join(self.image_root, name)) |
|
67 |
|
68 # ensure the path points inside the data root |
|
69 if not path.startswith(self.image_root): |
|
70 raise exceptions.NotFound(name) |
|
71 |
|
72 return name, path |
|
73 |
|
74 def get_image (self, url): |
|
75 """ |
|
76 Return Image object. |
|
77 """ |
|
78 |
|
79 name, path = self.lookup_image(url) |
|
80 |
|
81 # get Image object |
|
82 image = self.image_cache.get(path) |
|
83 |
|
84 if not image: |
|
85 # open |
|
86 image = pypngtile.Image(path) |
|
87 |
|
88 # check |
|
89 if image.status() not in (pypngtile.CACHE_FRESH, pypngtile.CACHE_STALE): |
|
90 raise exceptions.InternalServerError("Image cache not available: {name}".format(name=name)) |
|
91 |
|
92 # load |
|
93 image.open() |
|
94 |
|
95 # cache |
|
96 self.image_cache[path] = image |
|
97 |
|
98 return image |
|
99 |
|
100 def render_region (self, request, image): |
46 def render_region (self, request, image): |
101 """ |
47 """ |
102 Handle request for an image region |
48 Handle request for an image region |
103 """ |
49 """ |
104 |
50 |
145 """ |
91 """ |
146 Handle request for an image |
92 Handle request for an image |
147 """ |
93 """ |
148 |
94 |
149 try: |
95 try: |
150 image = self.get_image(request.path) |
96 image, name = self.get_image(request.path) |
151 except pypngtile.Error as error: |
97 except pypngtile.Error as error: |
152 raise exceptions.BadRequest(str(error)) |
98 raise exceptions.BadRequest(str(error)) |
153 |
99 |
154 if 'w' in request.args and 'h' in request.args and 'x' in request.args and 'y' in request.args: |
100 if 'w' in request.args and 'h' in request.args and 'x' in request.args and 'y' in request.args: |
155 png = self.render_region(request, image) |
101 png = self.render_region(request, image) |