KMLMiddleware

 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
27
28
from cStringIO import StringIO
import zipfile

class KMLMiddleware(object):
    """
    Middleware for serving KML data and optionally converting it to KMZ if the right extension is used.
    """
    def process_response(self, request, response):
        request_file = request.path.split("/")[-1]

        if request_file.lower().endswith(".kmz"):
            kmz = StringIO()
            f = zipfile.ZipFile(kmz, 'w', zipfile.ZIP_DEFLATED)
            save_file_name = request_file[:request_file.lower().rfind(".kmz")] # strips off the .kmz extension
            f.writestr('%s.kml' % save_file_name, response.content)
            f.close()
            response.content = kmz.getvalue()
            kmz.close()
            response['Content-Type']        = 'application/vnd.google-earth.kmz'
            response['Content-Disposition'] = 'attachment; filename=%s.kmz' % save_file_name
            response['Content-Length']      = str(len(response.content))
        if request_file.lower().endswith(".kml"):
            save_file_name = request_file[:request_file.lower().rfind(".kml")] # strips off the .kmz extension
            response['Content-Type']        = 'application/vnd.google-earth.kml+xml'
            response['Content-Disposition'] = 'attachment; filename=%s.kml' % save_file_name
            response['Content-Length']      = str(len(response.content))
            
        return response

More like this

  1. Effective content caching for mass-load site using redirect feature by nnseva 2 years, 9 months ago
  2. SSL Middleware for Webfaction by parlar 6 years, 11 months ago
  3. Interactive Profiling Middleware by sfllaw 3 years, 8 months ago
  4. Debug middleware for displaying sql queries and template loading info when ?debug=true by SEJeff 3 years ago
  5. utf8-friendly dumpdata management command (no escape symbols) #3 by inductor 11 months, 3 weeks ago

Comments

mhulse (on September 8, 2011):

Works great! Thank you. :)

#

mhulse (on September 11, 2011):

I noticed that the KML file does not update when new entries are added to my database... Is this by design? How would I update the KML view to update the KML output? Maybe I am missing something here?

#

mhulse (on September 16, 2011):

Scratch my last comment... The new class-based-generic views and my cache back end is giving me guff! Thanks again!

#

(Forgotten your password?)