1 from django.contrib.sitemaps import Sitemap
2 from forum.models import Question
3 from django.conf import settings
4 from django.http import HttpResponse, Http404
5 from django.template import loader
6 from django.core import urlresolvers
7 from django.utils.encoding import smart_str
8 from django.core.paginator import EmptyPage, PageNotAnInteger
10 def index(request, sitemaps):
12 for section, site in sitemaps.items():
14 pages = site().paginator.num_pages
16 pages = site.paginator.num_pages
17 sitemap_url = urlresolvers.reverse('sitemap_section_index', kwargs={'section': section})
18 sites.append('%s%s' % (settings.APP_URL, sitemap_url))
20 xml = loader.render_to_string('sitemap_index.xml', {'sitemaps': sites})
21 return HttpResponse(xml, mimetype='application/xml')
23 def sitemap_section_index(request, section, sitemaps):
25 sitemap = sitemaps[section]()
27 raise Http404("Sitemap doesn't exist")
29 paginator = sitemap.paginator
33 for page in paginator.page_range:
34 location = urlresolvers.reverse('sitemap_section_page', kwargs={ 'page' : page, 'section' : section })
35 location = '%s%s' % (settings.APP_URL, location)
36 locations.append(location)
38 xml = loader.render_to_string('sitemap_section_index.xml', { 'locations' : locations, })
39 return HttpResponse(xml, mimetype='application/xml')
41 def sitemap(request, sitemaps, section=None, page=1):
43 if section is not None:
44 if section not in sitemaps:
45 raise Http404("No sitemap available for section: %r" % section)
46 maps.append(sitemaps[section])
48 maps = sitemaps.values()
53 urls.extend(site().get_urls(page=page))
55 urls.extend(site.get_urls(page=page))
57 raise Http404("Page %s empty" % page)
58 except PageNotAnInteger:
59 raise Http404("No page '%s'" % page)
60 xml = smart_str(loader.render_to_string('sitemap.xml', {'urlset': urls}))
61 return HttpResponse(xml, mimetype='application/xml')
63 class OsqaSitemap(Sitemap):
68 return Question.objects.filter_state(deleted=False).order_by('id')
70 def lastmod(self, obj):
71 return obj.last_activity_at
73 def location(self, obj):
74 return obj.get_absolute_url()
76 def __get(self, name, obj, default=None):
78 attr = getattr(self, name)
79 except AttributeError:
85 def get_urls(self, page=1):
87 for item in self.paginator.page(page).object_list:
88 loc = "%s%s" % (settings.APP_URL, self.__get('location', item))
91 'lastmod': self.__get('lastmod', item, None),
92 'changefreq': self.__get('changefreq', item, None),
93 'priority': self.__get('priority', item, None)