-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathtile_server.py
executable file
·87 lines (66 loc) · 2.59 KB
/
tile_server.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#! /usr/bin/env python3
from http import HTTPStatus
from http.server import HTTPServer, SimpleHTTPRequestHandler
import os
import os.path
import re
import stat
import sys
import map_utils
class TileServer(SimpleHTTPRequestHandler):
def __init__(self, request, client, server, atlas):
self.atlas = atlas
super().__init__(request, client, server)
def do_GET(self):
try:
# _ gets '' because self.path is absolute
_, z, x, y_ext = self.path.split('/')
except ValueError:
self.send_error(HTTPStatus.BAD_REQUEST, f"bad tile spec '{self.path}' .")
else:
# TODO: make sure ext matches the file type we return
# TODO: support JPEG
y, ext = os.path.splitext(y_ext)
tile = map_utils.Tile(*[ int(i) for i in (z, x, y) ])
# TODO: implement 'depth first'; that is, sort maps somehow
# will need a tree, probably, beware of overlapping maps
found = False
for name, backend in self.atlas.items(): #
if tile in backend:
found = True
break
if found:
if backend.fs_based:
full_path = os.path.join(name, self.path)
size = os.stat(full_path).st_size
else:
backend.fetch(tile)
size = len(tile.data)
self.send_response(HTTPStatus.OK)
self.send_header('Content-Type', 'image/png')
self.send_header('Content-Length', size)
self.end_headers()
if backend.fs_based:
# create a socket to use high level sendfile()
sender = socket.fromfd(self.wfile.raw.fileno())
sender.sendfile(open(full_path))
else:
self.wfile.write(tile.data)
else:
self.send_error(HTTPStatus.NOT_FOUND, 'Tile not found.')
def main():
maps = sys.argv[1:]
atlas = {}
# splitext() returns the leading dot
mbt_exts = re.compile(r'\.(mbt|mbtiles|sqlite|sqlitedb)')
for map in maps:
basename, ext = os.path.splitext(map)
if mbt_exts.match(ext) is not None:
atlas[basename] = map_utils.MBTilesBackend(map, None, ro=True)
elif stat.S_ISDIR(os.stat(map).st_mode):
atlas[basename] = map_utils.DiskBackend(map)
# TODO: use aio
server = HTTPServer(('', 4847), lambda *a: TileServer(*a, atlas))
server.serve_forever()
if __name__ == '__main__':
main()