Generating sitemaps in Django

I did the generation of sitemaps according to this guide, but the site is large, and the map is generated very long, more than a minute. Also, the server is not very fast, so this is an extra load for it.

How to save the generation result to a file (sitemap.xml), and not to give on request? And the search engine will already take it directly from the file.

Author: Nicolas Chabanovsky, 2012-08-07

4 answers

The django.contrib.sitemaps view.views. sitemap (which generates xml) returns HttpResponse:

return HttpResponse(xml, mimetype='application/xml')

I think we should get it from the view and pull the xml (so as not to change the method itself)

I.e. you generate once sitemap.xml using django. contrib. sitemaps.views. sitemap, you learn from it HttpResponse, from it you get yourself sitemap.xml and save it on the server. Each time you change the structure of the site, it must be generated again (here, perhaps, the Observer pattern will help you). when accessing the url sitemap.xml another view should be called, giving an HttpResponse, which will contain sitemap.xml

 0
Author: Ekkertan, 2012-08-08 07:29:24

I will give my solution, I am sure it will be useful to someone. Based on the answer @Ekkertan.

from django.contrib.sitemaps.views import sitemap
from django.http import HttpResponse

def generic(request):
    if not request.user.is_superuser: #Чтобы никто не начал злоупотреблять
        return HttpResponse('You not admin')

    sitemaps = {
        'news': NewsItemSitemap,
        'articles': ArticleItemSitemap,
    }

    try:
        xml = sitemap(request, sitemaps)

        f = open(settings.ABSOLUTE_MEDIA + 'sitemap.xml', 'w')
        f.write(xml.rendered_content.encode("utf-8"))
        f.close()
        return HttpResponse('Success')
    except:
        return HttpResponse('Error')

In this way, using the link linked to the generic function, superuser only, we will get a file with the generated site map. Then it remains in urls.py write to /sitemap.xml give the file back sitemap.xml

That's all, now we either set the task in cron, or in the admin panel, click "Generate sitemap".

PS.. As it turned out, in different versions of Django, different the methods for this xml. rendered_content may not work. Then we write xml. content or look at dir (xml) and select the desired method. .encode ("utf-8") may or may not be needed, depending on the circumstances.

 2
Author: trec, 2012-08-10 06:11:59
 0
Author: LennyLip, 2015-01-19 09:41:53

Everything is much simpler.

  1. Creating an index sitemap
  2. Using cache_page()

More details here.

Read the official docks and you will be happy.

 0
Author: Lev, 2015-04-21 13:10:51