Last active
February 15, 2021 18:37
-
-
Save kristofgilicze/ea65c24a47c94fdb74af49f0c1ebaa51 to your computer and use it in GitHub Desktop.
Simple Tile server Blueprint for Flask Python framework integration
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import sqlite3 | |
from io import BytesIO | |
from flask import g | |
from flask import abort | |
from flask import Blueprint | |
from flask import current_app | |
blueprint = Blueprint( | |
name='map_tiles', | |
import_name=__name__, | |
) | |
@blueprint.before_request | |
def before_request(): | |
""" | |
Ensure database is connected for each request | |
""" | |
g.db = sqlite3.connect("map.mbtiles") | |
@blueprint.teardown_request | |
def teardown_request(exception): | |
""" | |
Cleanup database afterwards | |
""" | |
if hasattr(g, 'db'): | |
g.db.close() | |
@blueprint.route("/map-tiles/<int:zoom>/<int:column>/<int:row>.png") | |
def query_tile(zoom, column, row): | |
""" | |
Get a tile from the MBTiles database | |
:param zoom: | |
:param column: | |
:param row: | |
""" | |
# row = (2 ** zoom) - 1 - row | |
cursor = g.db.execute( | |
""" | |
SELECT tile_data FROM tiles | |
WHERE zoom_level = ? AND tile_column = ? AND tile_row = ?; | |
""", (zoom, column, row) | |
) | |
result = cursor.fetchone() | |
if not result: | |
abort(404) | |
the_image = bytes(result[0]) | |
return current_app.response_class( | |
BytesIO(the_image).read(), | |
mimetype='image/png' | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment