Skip to content

Instantly share code, notes, and snippets.

@soiqualang
Forked from schoenobates/mbtile-server.py
Created August 7, 2023 14:33
Show Gist options
  • Save soiqualang/43321a9de013f8f5793301c21a3d840e to your computer and use it in GitHub Desktop.
Save soiqualang/43321a9de013f8f5793301c21a3d840e to your computer and use it in GitHub Desktop.
Really quick and dirty way to serve tiles from a MBTiles file
#!/usr/bin/env python
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
import re
import sqlite3 as sqlite
# Hacky serving of MBtile data
# Put filename to the MBTiles file below: this could be done with cmd line options
# but this is a hack so there ....
con = sqlite.connect('<MBTILES-FILE-HERE>')
class MBTileHandler(BaseHTTPRequestHandler):
ZXY = re.compile('.*/(\d+)/(\d+)/(\d+)\..*')
def do_GET(self):
try:
if self.path.endswith(".png"):
self.send_response(200)
self.send_header('Content-type','image/png')
self.end_headers()
print(self.path)
m = self.ZXY.match(self.path)
sql = "select * from tiles where zoom_level = {0} and tile_column = {1} and tile_row = {2}".format(m.group(1), m.group(2), m.group(3))
cur = con.cursor()
for row in cur.execute(sql):
self.wfile.write(row[3])
cur.close()
return
except IOError:
self.send_error(404,'File Not Found: %s' % self.path)
def main():
try:
server = HTTPServer(('', 8090), MBTileHandler)
server.serve_forever()
except KeyboardInterrupt:
print 'shutting down server'
if server:
server.socket.close()
con.close()
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment