mapserver/servemaps

64 lines
1.9 KiB
Text
Raw Permalink Normal View History

2021-04-21 22:08:35 -04:00
#!/usr/bin/env python
"""
Small flask server to serve map tiles.
"""
from gevent import monkey
monkey.patch_all()
from gevent.pywsgi import WSGIServer
2021-04-21 22:08:35 -04:00
from argparse import ArgumentParser
from http import HTTPStatus
from os import getcwd
import importlib.util
2021-04-21 22:08:35 -04:00
import errno
import os.path
import sys
from flask import Flask, send_file, Response, render_template
# Parse Arguments
parser = ArgumentParser(description="Map Tile Server")
parser.add_argument(
"--tile-path",
type=str,
help="Location of map tiles on the filesystem",
default=f"{os.path.expanduser('~')}/.local/share/marble/maps/earth/openstreetmap"
)
parser.add_argument("--port", type=int, help="Port to bind to.", default=9001)
args = vars(parser.parse_args())
# Try to locate mapserver folder
root_path = getcwd() + "/mapserver"
2021-04-21 22:08:35 -04:00
if not os.path.isdir(root_path):
spec_location = importlib.util.find_spec('mapserver')
if spec_location is None or spec_location.origin is None:
print("mapserver folder is not in current directory or installed.")
sys.exit(1)
root_path = os.path.dirname(spec_location.origin)
app = Flask(__name__, root_path=root_path)
@app.route('/tiles/<zoom>/<y>/<x>')
def tiles(zoom, y, x):
"""Serve tiles directly from filesystem if found."""
filename = args['tile_path'] + f"/{zoom}/{x}/{y}.jpg"
if os.path.isfile(filename):
return send_file(filename)
return Response(status=HTTPStatus.NOT_FOUND)
@app.route('/')
def index():
"""Return a sample fullscreen map application."""
return render_template("index.html")
if __name__ == '__main__':
try:
http_server = WSGIServer(('', args['port']), app)
print(f"Starting map server on http://localhost:{args['port']}")
http_server.serve_forever()
2021-04-21 22:08:35 -04:00
except OSError as e:
if e.errno == errno.EADDRINUSE:
print("Address-Port Combination in use. Is another servemaps running?")
os._exit(errno.EADDRINUSE)
raise e