-
Notifications
You must be signed in to change notification settings - Fork 4
/
mbtileserver.py
85 lines (62 loc) · 1.93 KB
/
mbtileserver.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
"""
mbtileserver.py
===============
A minimal Flask application for serving map tiles from an MBTiles file.
Quick Usage:
MBTILES_PATH=/path/to/my.mbtiles python mbtileserver.py
Copyright 2013 Evan Friis
License: MIT
"""
from flask import Flask, g, abort, Blueprint, current_app
from flask.ext.cache import Cache
import os
import sqlite3
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO # NOQA
frontend = Blueprint('frontend', __name__)
cache = Cache()
@frontend.before_request
def before_request():
"""Ensure database is connected for each request """
g.db = sqlite3.connect(current_app.config['MBTILES_PATH'])
@frontend.teardown_request
def teardown_request(exception):
"""Cleanup database afterwards """
if hasattr(g, 'db'):
g.db.close()
@frontend.route("/<int:zoom>/<int:column>/<int:row>.png")
@cache.cached(timeout=300)
def query_tile(zoom, column, row):
"""Get a tile from the MBTiles database """
query = 'SELECT tile_data FROM tiles '\
'WHERE zoom_level = ? AND tile_column = ? AND tile_row = ?;'
cur = g.db.execute(query, (zoom, column, row))
results = cur.fetchall()
if not results:
abort(404)
the_image = results[0][0]
return current_app.response_class(
StringIO(the_image).read(),
mimetype='image/png'
)
def create_app(mbtiles=None, cache_config=None):
"""Initialize the application with a given configuration.
mbtiles must be a path to the MBTiles sqlite file.
"""
app = Flask(__name__)
app.config.update({
'MBTILES_PATH': mbtiles
})
app.register_blueprint(frontend)
cache.init_app(app, config=cache_config)
return app
if __name__ == "__main__":
app = create_app(
mbtiles=os.environ['MBTILES_PATH'],
cache_config={
'CACHE_TYPE': 'simple',
}
)
app.run(debug=True, port=os.environ.get('MBTILES_PORT', 41815))