我的django app sitemap.py看起来像这样:
class DetailViewSitemap(Sitemap):
priority = 0.8
changefreq = 'hourly'
def items(self):
objs = MyApp.objects.all().distinct('slug')
return objs
..而我的models.py,believeinetlky定义了一个类似的方法:
@models.permalink
def get_absolute_url(self):
try:
return ('detail', [self.slug])
except:
return None
一切正常,但我现在意识到谷歌在一个站点地图中不允许超过50k的链接 - 不幸的是我有超过50k的链接。
所以,我的问题是我如何分割我的站点地图,以便它生成在这个应用程序上说连续的站点地图?所以,我想要的是:
http://mywebapp.com/sitemap0.xml
http://mywebapp.com/sitemap1.xml
...
..如果这是可能的话!
答案 0 :(得分:1)
解决此问题的一种方法是将大型站点地图分成一组较小的站点地图。例如,我已经通过标题的首字母为Articles构建了单独的站点地图。因此,对于alpahabet中的每个字母,都会有一个站点地图文件。如果您想使用字母数字字符也可以,但是在我们的情况下,字母可以正常工作。 Python内置方法ascii_lowercase将返回一个字母字符数组,我们可以循环使用它们来构建每个站点地图。
from datetime import date
from string import ascii_lowercase
from django.contrib.sitemaps import Sitemap
from .models import Article
def build_sitemaps():
sitemap = {}
for char in ascii_lowercase:
article_sitemap = ArticleSitemap(letter=char)
sitemap[char] = article_sitemap
return sitemap
class ArticleSitemap(Sitemap):
changefreq = "never"
priority = 0.5
def __init__(self, letter='a'):
self.letter = letter.lower()
super(ArticleSitemap, self).__init__()
def items(self):
today = date.today()
return Article.objects.filter(
status=Article.PUBLISHED,
title__istartswith=self.letter,
).exclude(
publish_date__gt=today,
).order_by('-publish_date')
下面,我还添加了站点地图的缓存,这确实很棒。然后像这样在urls.py中添加站点地图:
from django.contrib.sitemaps import views as sitemaps_views
from django.views.decorators.cache import cache_page
from articles.sitemaps import build_sitemaps
urlpatterns = [
url(r'^sitemap\.xml$', cache_page(86400)(sitemaps_views.index), {'sitemaps': build_sitemaps()}),
url(r'^sitemap-(?P<section>.+)\.xml$', cache_page(86400)(sitemaps_views.sitemap), {'sitemaps': build_sitemaps()},
name='django.contrib.sitemaps.views.sitemap'),
]
如果您需要更多有关如何使用Sitemaps索引实现的代码段,请在我的网站https://www.ronbeltran.com/2018/11/generating-large-xml-sitemaps-django/中查看此帖子
答案 1 :(得分:-2)
Create an index sitemap和Django将自动对详细站点地图进行分页,如下所示:
http://mywebapp.com/sitemap-details.xml
http://mywebapp.com/sitemap-details.xml?page=1
...