1 from django.contrib.sitemaps import Sitemap
2 from forum.models import Question
3 from forum.settings import QUESTIONS_SITEMAP_LIMIT, QUESTIONS_SITEMAP_CHANGEFREQ
4 from django.conf import settings
5 from django.http import HttpResponse, Http404
6 from django.template import loader
7 from django.core import urlresolvers
8 from django.utils.encoding import smart_str
9 from django.core.paginator import EmptyPage, PageNotAnInteger
11 def index(request, sitemaps):
13 for section, site in sitemaps.items():
15 pages = site().paginator.num_pages
17 pages = site.paginator.num_pages
18 sitemap_url = urlresolvers.reverse('sitemap_section_index', kwargs={'section': section})
19 sites.append('%s%s' % (settings.APP_URL, sitemap_url))
21 xml = loader.render_to_string('sitemap_index.xml', {'sitemaps': sites})
22 return HttpResponse(xml, mimetype='application/xml')
24 def sitemap_section_index(request, section, sitemaps):
26 sitemap = sitemaps[section]()
28 raise Http404("Sitemap doesn't exist")
30 paginator = sitemap.paginator
34 for page in paginator.page_range:
35 location = urlresolvers.reverse('sitemap_section_page', kwargs={ 'page' : page, 'section' : section })
36 location = '%s%s' % (settings.APP_URL, location)
37 locations.append(location)
39 xml = loader.render_to_string('sitemap_section_index.xml', { 'locations' : locations, })
40 return HttpResponse(xml, mimetype='application/xml')
42 def sitemap(request, sitemaps, section=None, page=1):
44 if section is not None:
45 if section not in sitemaps:
46 raise Http404("No sitemap available for section: %r" % section)
47 maps.append(sitemaps[section])
49 maps = sitemaps.values()
54 urls.extend(site().get_urls(page=page))
56 urls.extend(site.get_urls(page=page))
58 raise Http404("Page %s empty" % page)
59 except PageNotAnInteger:
60 raise Http404("No page '%s'" % page)
61 xml = smart_str(loader.render_to_string('sitemap.xml', {'urlset': urls}))
62 return HttpResponse(xml, mimetype='application/xml')
64 class OsqaSitemap(Sitemap):
65 limit = QUESTIONS_SITEMAP_LIMIT
66 changefreq = QUESTIONS_SITEMAP_CHANGEFREQ
69 return Question.objects.filter_state(deleted=False).order_by('id')
71 def lastmod(self, obj):
72 return obj.last_activity_at
74 def location(self, obj):
75 return obj.get_absolute_url()
77 def __get(self, name, obj, default=None):
79 attr = getattr(self, name)
80 except AttributeError:
86 def get_urls(self, page=1):
88 for item in self.paginator.page(page).object_list:
89 loc = "%s%s" % (settings.APP_URL, self.__get('location', item))
92 'lastmod': self.__get('lastmod', item, None),
93 'changefreq': self.__get('changefreq', item, None),
94 'priority': self.__get('priority', item, None)