Skip to content

Instantly share code, notes, and snippets.

@symroe
Last active August 5, 2025 12:10
Show Gist options
  • Select an option

  • Save symroe/7a58f8998b963d92f42a413f3dd4efca to your computer and use it in GitHub Desktop.

Select an option

Save symroe/7a58f8998b963d92f42a413f3dd4efca to your computer and use it in GitHub Desktop.
export_divisions_pmtiles.py
import os
import subprocess
from django.core.management.base import BaseCommand
from django.db import connection
class Command(BaseCommand):
help = 'Export divisions as GeoJSON and create a pmtile using ogr2ogr and tippecanoe'
def add_arguments(self, parser):
parser.add_argument('divisionset_id', type=str, help='The ID of the divisionset to export')
def handle(self, *args, **kwargs):
divisionset_id = kwargs['divisionset_id']
geojson_file = f'{divisionset_id}_divisions.geojson'
pmtile_file = f'{divisionset_id}_divisions.pmtiles'
# Get database connection settings from Django's connection object
db_settings = connection.settings_dict
dbname = db_settings['NAME']
user = db_settings['USER']
password = db_settings['PASSWORD']
host = db_settings['HOST']
port = db_settings['PORT'] or 5432 # Default PostgreSQL port
# Construct the ogr2ogr command
ogr_command = f'ogr2ogr -f "GeoJSON" {geojson_file} "PG:dbname={dbname} user={user} password={password} host={host} port={port}" -sql "SELECT g.*, d.name as division_name, d.id as division_id FROM organisations_divisiongeography g JOIN organisations_organisationdivision d ON g.division_id = d.id WHERE d.divisionset_id = \'{divisionset_id}\'"'
# Execute the command
try:
subprocess.run(ogr_command, shell=True, check=True)
# Create a temporary mbtiles file using tippecanoe
pmtiles_file = f'{divisionset_id}_divisions.pmtiles'
tippecanoe_command = f'tippecanoe -o {pmtiles_file} -zg --drop-rate=2 --drop-densest-as-needed {geojson_file}'
subprocess.run(tippecanoe_command, shell=True, check=True)
# Clean up temporary files
os.remove(geojson_file)
self.stdout.write(self.style.SUCCESS(f'Successfully created pmtile {pmtile_file}'))
except subprocess.CalledProcessError as e:
self.stderr.write(self.style.ERROR(f'Error exporting divisions: {e}'))
return # Exit early on error
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment