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