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.
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
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.
Now there is a great app