| 1 |
import zipfile |
| 2 |
from io import BytesIO |
| 3 |
|
| 4 |
from django.conf import settings |
| 5 |
from django.http import HttpResponse |
| 6 |
from django.template import loader |
| 7 |
|
| 8 |
# NumPy supported? |
| 9 |
try: |
| 10 |
import numpy |
| 11 |
except ImportError: |
| 12 |
numpy = False |
| 13 |
|
| 14 |
|
| 15 |
def compress_kml(kml): |
| 16 |
"Return compressed KMZ from the given KML string." |
| 17 |
kmz = BytesIO() |
| 18 |
with zipfile.ZipFile(kmz, "a", zipfile.ZIP_DEFLATED) as zf: |
| 19 |
zf.writestr("doc.kml", kml.encode(settings.DEFAULT_CHARSET)) |
| 20 |
kmz.seek(0) |
| 21 |
return kmz.read() |
| 22 |
|
| 23 |
|
| 24 |
def render_to_kml(*args, **kwargs): |
| 25 |
"Render the response as KML (using the correct MIME type)." |
| 26 |
return HttpResponse( |
| 27 |
loader.render_to_string(*args, **kwargs), |
| 28 |
content_type="application/vnd.google-earth.kml+xml", |
| 29 |
) |
| 30 |
|
| 31 |
|
| 32 |
def render_to_kmz(*args, **kwargs): |
| 33 |
""" |
| 34 |
Compress the KML content and return as KMZ (using the correct |
| 35 |
MIME type). |
| 36 |
""" |
| 37 |
return HttpResponse( |
| 38 |
compress_kml(loader.render_to_string(*args, **kwargs)), |
| 39 |
content_type="application/vnd.google-earth.kmz", |
| 40 |
) |