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.
 
 
 
 

85 lines
2.9 KiB

  1. import datetime
  2. from calendar import timegm
  3. from functools import wraps
  4. from django.contrib.sites.shortcuts import get_current_site
  5. from django.core import urlresolvers
  6. from django.core.paginator import EmptyPage, PageNotAnInteger
  7. from django.http import Http404
  8. from django.template.response import TemplateResponse
  9. from django.utils.http import http_date
  10. def x_robots_tag(func):
  11. @wraps(func)
  12. def inner(request, *args, **kwargs):
  13. response = func(request, *args, **kwargs)
  14. response['X-Robots-Tag'] = 'noindex, noodp, noarchive'
  15. return response
  16. return inner
  17. @x_robots_tag
  18. def index(request, sitemaps,
  19. template_name='sitemap_index.xml', content_type='application/xml',
  20. sitemap_url_name='django.contrib.sitemaps.views.sitemap'):
  21. req_protocol = request.scheme
  22. req_site = get_current_site(request)
  23. sites = []
  24. for section, site in sitemaps.items():
  25. if callable(site):
  26. site = site()
  27. protocol = req_protocol if site.protocol is None else site.protocol
  28. sitemap_url = urlresolvers.reverse(
  29. sitemap_url_name, kwargs={'section': section})
  30. absolute_url = '%s://%s%s' % (protocol, req_site.domain, sitemap_url)
  31. sites.append(absolute_url)
  32. for page in range(2, site.paginator.num_pages + 1):
  33. sites.append('%s?p=%s' % (absolute_url, page))
  34. return TemplateResponse(request, template_name, {'sitemaps': sites},
  35. content_type=content_type)
  36. @x_robots_tag
  37. def sitemap(request, sitemaps, section=None,
  38. template_name='sitemap.xml', content_type='application/xml'):
  39. req_protocol = request.scheme
  40. req_site = get_current_site(request)
  41. if section is not None:
  42. if section not in sitemaps:
  43. raise Http404("No sitemap available for section: %r" % section)
  44. maps = [sitemaps[section]]
  45. else:
  46. maps = sitemaps.values()
  47. page = request.GET.get("p", 1)
  48. urls = []
  49. for site in maps:
  50. try:
  51. if callable(site):
  52. site = site()
  53. urls.extend(site.get_urls(page=page, site=req_site,
  54. protocol=req_protocol))
  55. except EmptyPage:
  56. raise Http404("Page %s empty" % page)
  57. except PageNotAnInteger:
  58. raise Http404("No page '%s'" % page)
  59. response = TemplateResponse(request, template_name, {'urlset': urls},
  60. content_type=content_type)
  61. if hasattr(site, 'latest_lastmod'):
  62. # if latest_lastmod is defined for site, set header so as
  63. # ConditionalGetMiddleware is able to send 304 NOT MODIFIED
  64. lastmod = site.latest_lastmod
  65. response['Last-Modified'] = http_date(
  66. timegm(
  67. lastmod.utctimetuple() if isinstance(lastmod, datetime.datetime)
  68. else lastmod.timetuple()
  69. )
  70. )
  71. return response