Debian Codegraph @

django/contrib/gis/sitemaps/kml.py

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