#!/usr/bin/env python3 """Minimal local tile server for the stag/sgeo tests. Serves solid-colour 256x256 PNG tiles for any /z/x/y.png, so the sgeo tests do not depend on the network. sgeo is pointed at it with $SGEO_TILE_BASE=http://127.0.0.1:. Usage: tile_server.py --port-file FILE Binds an ephemeral port, writes the port number to FILE, then serves forever (the test runner kills it on exit). """ import argparse import binascii import struct import zlib from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer def chunk(typ, data): c = struct.pack(">I", len(data)) + typ + data return c + struct.pack(">I", binascii.crc32(typ + data) & 0xFFFFFFFF) def make_tile(x, y): # Solid fill, shade varies slightly with the tile so stitching is # visible; plus a 1px darker border. base = 225 + ((x + y) % 3) * 5 row = b"\x00" + bytes([base, base, base]) * 256 rows = [row] * 256 raw = b"".join(rows) ihdr = struct.pack(">IIBBBBB", 256, 256, 8, 2, 0, 0, 0) png = b"\x89PNG\r\n\x1a\n" png += chunk(b"IHDR", ihdr) png += chunk(b"IDAT", zlib.compress(raw, 6)) png += chunk(b"IEND", b"") return png class Handler(BaseHTTPRequestHandler): def do_GET(self): parts = self.path.strip("/").split("/") try: z, x, y = int(parts[0]), int(parts[1]), int(parts[2].split(".")[0]) assert 0 <= z <= 22 and 0 <= x < (1 << z) and 0 <= y < (1 << z) except Exception: self.send_response(404) self.end_headers() return body = make_tile(x, y) self.send_response(200) self.send_header("Content-Type", "image/png") self.send_header("Content-Length", str(len(body))) self.end_headers() self.wfile.write(body) def log_message(self, *args): pass def main(): ap = argparse.ArgumentParser() ap.add_argument("--port-file", required=True) args = ap.parse_args() srv = ThreadingHTTPServer(("127.0.0.1", 0), Handler) with open(args.port_file, "w") as f: f.write(str(srv.server_address[1])) srv.serve_forever() if __name__ == "__main__": main()