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