- April 17, 2008
- middleware kml kmz google-earth
- 1 (after 1 ratings)
Serving KML from your Django webapp to feed Google-earth isn't that hard, it's just some fun with templates, plus some headers. But serving a compressed version of your KML needs a trick.
KMZ isn't just zipped KML. A good KMZ file is a zipped file that decompress to a file called 'doc.kml', which is a KML file.
So, I suppose 'http://yourdomain.com/kml/' points to a view generating a well-formed KML. I even suppose that 'http://yourdomain.com/kmz/' points to the same view, but it will serve KMZ instead that KML: no change needed in your code!
If your webapps serves more than one KML file you just need to append the new KMZ urls to your urls.py, pointing to the very same view serving the KML version. Then add that urls to the list in this middleware. As an example I included a 'http://yourdomain.com/kml/restricted/' to 'http://yourdomain.com/kmz/restricted/' conversion.
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
from cStringIO import StringIO import zipfile class KMZMiddleware(object): """ Middleware for serving KML data or converting it to KMZ. """ def process_response(self, request, response): if request.path in ('/kmz/', '/kmz/restricted/', ): kmz = StringIO() f = zipfile.ZipFile(kmz, 'w', zipfile.ZIP_DEFLATED) f.writestr('doc.kml', response.content) f.close() response.content = kmz.getvalue() kmz.close() response['Content-Type'] = 'application/vnd.google-earth.kmz' response['Content-Disposition'] = 'attachment; filename=foo.kmz' response['Content-Description'] = 'some description' response['Content-Length'] = str(len(response.content)) if request.path in ('/kml/', '/kml/restricted/', ): response['Content-Type'] = 'application/vnd.google-earth.kml+xml' response['Content-Disposition'] = 'attachment; filename=foo.kml' response['Content-Description'] = 'some description' response['Content-Length'] = str(len(response.content)) return response
More like this
- nginx x-accel-redirect protection of static files by sean 7 years, 4 months ago
- Send large files through Django, and how to generate Zip files by jcrocholl 7 years, 8 months ago
- JSON encoding middleware by kcarnold 6 years, 10 months ago
- KMLMiddleware by takinbo 4 years, 1 month ago
- Create OpenOffice documents by king 8 years, 1 month ago