pngtile.image: update for PNGTileApplication
authorTero Marttila <terom@qmsk.net>
Sat, 04 Oct 2014 01:02:20 +0300
changeset 168 260aa4a05e82
parent 167 16b600e927fe
child 169 b69ffcd1ecc7
pngtile.image: update for PNGTileApplication
bin/image-server
pngtile/image.py
static/pngtile/map.js
--- a/bin/image-server	Sat Oct 04 01:02:04 2014 +0300
+++ b/bin/image-server	Sat Oct 04 01:02:20 2014 +0300
@@ -20,7 +20,7 @@
     parser.add_argument('--debugger',   action='store_true',
             help="Debugger")
     
-    parser.add_argument('--tile-server',    metavar='URL', required=True,
+    parser.add_argument('--tiles-server',    metavar='URL', required=True,
             help="http://.../ URL to tileserver root")
     parser.add_argument('--static',     metavar='PATH', default='./static',
             help="Path to /static")
@@ -32,7 +32,7 @@
     application = pngtile.image.ImageApplication(
         image_root  = args.image_root,
 
-        tile_server = args.tile_server,
+        tiles_server = args.tiles_server,
     )
 
     werkzeug.serving.run_simple(args.listen, args.port, application,
--- a/pngtile/image.py	Sat Oct 04 01:02:04 2014 +0300
+++ b/pngtile/image.py	Sat Oct 04 01:02:20 2014 +0300
@@ -5,46 +5,16 @@
 
 from werkzeug import Request, Response, exceptions
 from werkzeug.utils import html, redirect
+import werkzeug.urls
 
 import pngtile.tile
-from pngtile.application import url, BaseApplication
+import pngtile.application
 import pypngtile
 
 import json
 import os, os.path
 
-def dir_list (root):
-    """
-        Yield a series of directory items to show for the given dir
-    """
-
-    for name in os.listdir(root):
-        path = os.path.join(root, name)
-
-        # skip dotfiles
-        if name.startswith('.'):
-            continue
-        
-        # show dirs
-        if os.path.isdir(path):
-            if not os.access(path, os.R_OK):
-                # skip inaccessible dirs
-                continue
-
-            yield name + '/'
-
-        # examine ext
-        if '.' in name:
-            name_base, name_type = name.rsplit('.', 1)
-        else:
-            name_base = name
-            name_type = None
-
-        # show .png files with a .cache file
-        if name_type in ImageApplication.IMAGE_TYPES and os.path.exists(os.path.join(root, name_base + '.cache')):
-            yield name
-
-class ImageApplication (BaseApplication):
+class ImageApplication (pngtile.application.PNGTileApplication):
 
     STYLESHEETS = (
         'https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css',
@@ -60,16 +30,42 @@
         '/static/pngtile/map.js',
     )
 
-    def __init__ (self, tile_server=None, **opts):
+    def __init__ (self, tiles_server=None, **opts):
         """
             http://.../ path to tileserver root
         """
 
-        BaseApplication.__init__(self, **opts)
+        super(ImageApplication, self).__init__(**opts)
                 
-        self.tile_server = tile_server
+        self.tiles_server = tiles_server
+
+    def tiles_url (self, name, **args):
+        return werkzeug.urls.Href(self.tiles_server)(name, **args)
+
+    def render_html (self, title, body, stylesheets=None, scripts=None, end=()):
+        if stylesheets is None:
+            stylesheets = self.STYLESHEETS
+
+        if scripts is None:
+            scripts = self.SCRIPTS
+
+        return html.html(lang='en', *[
+            html.head(
+                html.title(title),
+                *[
+                    html.link(rel='stylesheet', href=href) for href in stylesheets
+                ]
+            ),
+            html.body(
+                *(body + tuple(
+                    html.script(src=src) for src in scripts
+                ) + end)
+            ),
+        ])
+
 
     def render_dir_breadcrumb (self, name):
+        href = werkzeug.urls.Href('/')
         path = []
 
         yield html.li(html.a(href='/', *[u"Index"]))
@@ -78,7 +74,7 @@
             for part in name.split('/'):
                 path.append(part)
 
-                yield html.li(html.a(href=url('/', *path), *[part]))
+                yield html.li(html.a(href=href(*path), *[part]))
 
     def render_dir (self, request, name, items):
         """
@@ -120,16 +116,13 @@
         image_info = image.info()
 
         map_config = dict(
-            tile_url        = '{server}/{name}?x={x}&y={y}&zoom={z}',
-            tile_server     = self.tile_server.rstrip('/'),
-            tile_name       = name,
+            tiles_url       = self.tiles_url(name),
 
+            tile_url        = '{tiles_url}?x={x}&y={y}&zoom={z}',
             tile_size       = pngtile.tile.TILE_SIZE,
             tile_zoom       = pngtile.tile.MAX_ZOOM,
             
-            image_url       = '{server}/{name}?w={w}&h={h}&x={x}&y={y}&zoom={z}',
-            image_server    = self.tile_server.rstrip('/'),
-            image_name      = name,
+            image_url       = '{tiles_url}?w={w}&h={h}&x={x}&y={y}&zoom={z}',
             image_width     = image_info['img_width'],
             image_height    = image_info['img_height'],
         )
@@ -155,7 +148,7 @@
             # we generate HTML with relative links
             return redirect(request.path + '/')
 
-        items = sorted(dir_list(path))
+        items = sorted(self.list(request.path))
 
         html = self.render_dir(request, name, items)
 
@@ -168,7 +161,7 @@
 
         # backwards-compat redirect from frontend -> tile-server
         if all(attr in request.args for attr in ('cx', 'cy', 'w', 'h', 'zl')):
-            return redirect(url(self.tile_server, name,
+            return redirect(self.tiles_url(name,
                 w       = request.args['w'],
                 h       = request.args['h'],
                 x       = request.args['cx'],
@@ -176,10 +169,7 @@
                 zoom    = request.args['zl'],
             ))
 
-        try:
-            image, name = self.get_image(request.path)
-        except pypngtile.Error as error:
-            raise exceptions.BadRequest(str(error))
+        image, name = self.open(request.path)
 
         html = self.render_image(request, image, name)
 
@@ -190,7 +180,7 @@
             Handle request for an image
         """
 
-        name, path, type = self.lookup_path(request.path)
+        name, path, type = self.lookup(request.path)
         
         # determine handler
         if not type:
@@ -199,3 +189,15 @@
         else:
             return self.handle_image(request, name, path)
 
+    @Request.application
+    def __call__ (self, request):
+        """
+            WSGI entry point.
+        """
+
+        try:
+            return self.handle(request)
+
+        except exceptions.HTTPException as error:
+            return error
+
--- a/static/pngtile/map.js	Sat Oct 04 01:02:04 2014 +0300
+++ b/static/pngtile/map.js	Sat Oct 04 01:02:20 2014 +0300
@@ -73,8 +73,7 @@
     map.on('move', map_move);
 
     L.tileLayer(map_config.tile_url, {
-        server:             map_config.tile_server,
-        name:               map_config.tile_name,
+        tiles_url:          map_config.tiles_url,
         minZoom:            0,
         maxZoom:            map_config.tile_zoom,
         tileSize:           map_config.tile_size,
@@ -87,8 +86,7 @@
     // controls
     L.control.link({
         url:        map_config.image_url,
-        server:     map_config.image_server,
-        name:       map_config.image_name,
+        tiles_url:  map_config.tiles_url,
     }).addTo(map);
 
     // set position