You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

69 lines
2.5 KiB

  1. from django.apps import apps
  2. from django.contrib.gis.db.models.fields import GeometryField
  3. from django.contrib.sitemaps import Sitemap
  4. from django.core import urlresolvers
  5. from django.db import models
  6. class KMLSitemap(Sitemap):
  7. """
  8. A minimal hook to produce KML sitemaps.
  9. """
  10. geo_format = 'kml'
  11. def __init__(self, locations=None):
  12. # If no locations specified, then we try to build for
  13. # every model in installed applications.
  14. self.locations = self._build_kml_sources(locations)
  15. def _build_kml_sources(self, sources):
  16. """
  17. Goes through the given sources and returns a 3-tuple of
  18. the application label, module name, and field name of every
  19. GeometryField encountered in the sources.
  20. If no sources are provided, then all models.
  21. """
  22. kml_sources = []
  23. if sources is None:
  24. sources = apps.get_models()
  25. for source in sources:
  26. if isinstance(source, models.base.ModelBase):
  27. for field in source._meta.fields:
  28. if isinstance(field, GeometryField):
  29. kml_sources.append((source._meta.app_label,
  30. source._meta.model_name,
  31. field.name))
  32. elif isinstance(source, (list, tuple)):
  33. if len(source) != 3:
  34. raise ValueError('Must specify a 3-tuple of (app_label, module_name, field_name).')
  35. kml_sources.append(source)
  36. else:
  37. raise TypeError('KML Sources must be a model or a 3-tuple.')
  38. return kml_sources
  39. def get_urls(self, page=1, site=None, protocol=None):
  40. """
  41. This method is overridden so the appropriate `geo_format` attribute
  42. is placed on each URL element.
  43. """
  44. urls = Sitemap.get_urls(self, page=page, site=site, protocol=protocol)
  45. for url in urls:
  46. url['geo_format'] = self.geo_format
  47. return urls
  48. def items(self):
  49. return self.locations
  50. def location(self, obj):
  51. return urlresolvers.reverse('django.contrib.gis.sitemaps.views.%s' % self.geo_format,
  52. kwargs={'label': obj[0],
  53. 'model': obj[1],
  54. 'field_name': obj[2],
  55. }
  56. )
  57. class KMZSitemap(KMLSitemap):
  58. geo_format = 'kmz'