Django 站点地图索引示例

发布于 2024-08-04 13:17:19 字数 737 浏览 7 评论 0原文

我有以下模型关系:

class Section(models.Model):
    section = models.CharField(max_length=200, unique=True)
    name = models.CharField(max_length=200, blank = True)


class Article (models.Model):
    url = models.CharField(max_length = 30, unique=True)
    is_published = models.BooleanField()  
    section = models.ForeignKey(Section)

我需要为文章创建站点地图,其中包含部分的站点地图文件。我在这里阅读有关它的 django 文档 http://docs.djangoproject.com/ en/dev/ref/contrib/sitemaps/

但没有找到答案我该如何:

  1. 在这种情况下定义站点地图类
  2. 如何将部分参数传递到 url 文件中(如中所述 文档)
  3. 如果我定义了,我可以从哪里获取 {'sitemaps': sitemaps} 站点地图作为应用程序中另一个文件中的 python 类

I have following models relation:

class Section(models.Model):
    section = models.CharField(max_length=200, unique=True)
    name = models.CharField(max_length=200, blank = True)


class Article (models.Model):
    url = models.CharField(max_length = 30, unique=True)
    is_published = models.BooleanField()  
    section = models.ForeignKey(Section)

I need to create a sitemap for articles, which contains sitemap files for sections. I was reading django documentation about it here http://docs.djangoproject.com/en/dev/ref/contrib/sitemaps/

But didn't manage to find answer how can I:

  1. Define sitemap class in this case
  2. How can I pass section parameters into url file (as it's explained in
    the docs)
  3. From where can I get {'sitemaps': sitemaps} if I defined
    sitemap as a python class in another file in the application

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

蓬勃野心 2024-08-11 13:17:19

如果我理解正确的话,您想要使用站点地图索引,该索引将指向每个部分的单独站点地图 xml 文件。

Django 通过提供单独的站点地图视图来支持此功能 用于索引站点地图。

以前没有使用过该功能,但类似以下内容可能适用于您的情况。

### sitemaps.py
from django.contrib.sitemaps import GenericSitemap
from models import Section

all_sitemaps = {}
for section in Section.objects.all():

    info_dict = {
        'queryset': section.article_set.filter(is_published=True),
    }

    sitemap = GenericSitemap(info_dict,priority=0.6)

    # dict key is provided as 'section' in sitemap index view
    all_sitemaps[section.name] = sitemap

### urls.py
from sitemaps import all_sitemaps as sitemaps

...
...
...

urlpatterns += patterns('',
        (r'^sitemap.xml
, 'django.contrib.sitemaps.views.index', {'sitemaps': sitemaps}),
        (r'^sitemap-(?P<section>.+)\.xml
, 'django.contrib.sitemaps.views.sitemap', {'sitemaps': sitemaps}),
)

If i understand correctly you want to use sitemap index that would point at seperate sitemap xml files each for every section.

Django supports this feature by providing a separate sitemap view for index sitemaps.

Haven't used that feature before but something like the following would probably work in your case.

### sitemaps.py
from django.contrib.sitemaps import GenericSitemap
from models import Section

all_sitemaps = {}
for section in Section.objects.all():

    info_dict = {
        'queryset': section.article_set.filter(is_published=True),
    }

    sitemap = GenericSitemap(info_dict,priority=0.6)

    # dict key is provided as 'section' in sitemap index view
    all_sitemaps[section.name] = sitemap

### urls.py
from sitemaps import all_sitemaps as sitemaps

...
...
...

urlpatterns += patterns('',
        (r'^sitemap.xml
, 'django.contrib.sitemaps.views.index', {'sitemaps': sitemaps}),
        (r'^sitemap-(?P<section>.+)\.xml
, 'django.contrib.sitemaps.views.sitemap', {'sitemaps': sitemaps}),
)
吃素的狼 2024-08-11 13:17:19
Django==2.2
Python==3.6

这是在 Django 中使用站点地图索引的更好、更简单的方法,
通过将 django.contrib.sitemaps 添加到 settings.pyINSTALLED_APPS 中来安装项目中的 django.contrib.sitemaps
在您的应用程序中编写 sitemaps.py 文件并根据需要定义类。例如,在静态 URL 的 StaticViewSitemap 站点地图类中扩展 django.contrib.sitemap.Sitemap,确保所有静态 URL 的名称为 反向查找(从URL名称获取URL)

# app/sitemap.py

from django.contrib import sitemaps
from django.urls import reverse

class StaticViewSitemap(sitemaps.Sitemap):
    priority = 0.6
    changefreq = 'monthly'

    def items(self):
        # URLs names
        return ['index', 'aboutus', 'ourstory',]

    def location(self, item):
        return reverse(item)

导入urls.py中的所有站点地图
从 django.contrib.sitemaps.views 导入站点地图和索引
然后创建一个包含站点地图的字典

# urls.py

from django.contrib.sitemaps.views import sitemap, index
from app.sitemaps import StaticViewSitemap

# add as many as sitemap you need as one key
sitemaps = {
    "static" : StaticViewSitemap,
}
urlpatterns = [

    # sitemap.xml index will have all sitemap-......xmls index
    path('sitemap.xml', index, {'sitemaps': sitemaps}, name='django.contrib.sitemaps.views.index'),

    # sitemap-<section>.xml here <section> will be replaced by the key from sitemaps dict
    path('sitemap-<section>.xml', sitemap, {'sitemaps': sitemaps}, name='django.contrib.sitemaps.views.sitemap'),
]

这里您将有两个站点地图1.sitemaps.xml 2.sitemaps-static.xml
运行服务器打开 URL: http://localhost:8000/sitemap.xml

<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
    <sitemap>
        <loc>http://127.0.0.1:8000/sitemap-static.xml</loc>
    </sitemap>
</sitemapindex>

Django 自动创建了一个索引站点地图现在打开 URL:http://127.0.0.1:8000/sitemap-static.xml

<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
    <url>
        <loc>http://localhost:8000/</loc>
        <changefreq>monthly</changefreq>
        <priority>0.6</priority>
    </url>
    <url>
        <loc>http://localhost:8000/about-us</loc>
        <changefreq>monthly</changefreq>
        <priority>0.6</priority>
    </url>
    <url>
        <loc>http://localhost:8000/our-story</loc>
        <changefreq>monthly</changefreq>
        <priority>0.6</priority>
    </url>
</urlset>
Django==2.2
Python==3.6

Here is the better and easy way to use sitemap index in Django,
install django.contrib.sitemaps in the project by adding it to INSTALLED_APPS of settings.py.
Write sitemaps.py file in your apps and define classes as you need. Example extend django.contrib.sitemap.Sitemap in StaticViewSitemap sitemap class for static URLs, make sure your all static URL has the name for reverse lookup(getting URL from URL name)

# app/sitemap.py

from django.contrib import sitemaps
from django.urls import reverse

class StaticViewSitemap(sitemaps.Sitemap):
    priority = 0.6
    changefreq = 'monthly'

    def items(self):
        # URLs names
        return ['index', 'aboutus', 'ourstory',]

    def location(self, item):
        return reverse(item)

Import all sitemaps in urls.py
import sitemap and index from django.contrib.sitemaps.views
then create a dictionary with sitemaps

# urls.py

from django.contrib.sitemaps.views import sitemap, index
from app.sitemaps import StaticViewSitemap

# add as many as sitemap you need as one key
sitemaps = {
    "static" : StaticViewSitemap,
}
urlpatterns = [

    # sitemap.xml index will have all sitemap-......xmls index
    path('sitemap.xml', index, {'sitemaps': sitemaps}, name='django.contrib.sitemaps.views.index'),

    # sitemap-<section>.xml here <section> will be replaced by the key from sitemaps dict
    path('sitemap-<section>.xml', sitemap, {'sitemaps': sitemaps}, name='django.contrib.sitemaps.views.sitemap'),
]

Here you will have two sitemaps 1. sitemaps.xml 2. sitemaps-static.xml
Run server open URL: http://localhost:8000/sitemap.xml

<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
    <sitemap>
        <loc>http://127.0.0.1:8000/sitemap-static.xml</loc>
    </sitemap>
</sitemapindex>

Django automatically created an index of sitemaps now open URL: http://127.0.0.1:8000/sitemap-static.xml

<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
    <url>
        <loc>http://localhost:8000/</loc>
        <changefreq>monthly</changefreq>
        <priority>0.6</priority>
    </url>
    <url>
        <loc>http://localhost:8000/about-us</loc>
        <changefreq>monthly</changefreq>
        <priority>0.6</priority>
    </url>
    <url>
        <loc>http://localhost:8000/our-story</loc>
        <changefreq>monthly</changefreq>
        <priority>0.6</priority>
    </url>
</urlset>
楠木可依 2024-08-11 13:17:19

对我来说,接受的答案会影响开发和测试周期速度,因为它使 python manage.py 命令运行得更慢——我在数据库中要做的事情比这个例子多一些。

以下是我为缓解而所做的更改(适应示例)。还没有进行战斗测试,但这似乎可以解决问题(Python3):

### sitemaps.py

class SitemapLookup():
    """
    Instantiated class replaces the dictionary of {'sitemap-section': Sitemap} for urls.py
    Speeds up application load time by only querying the DB when a sitemap is first requested.
    """

    def __init__(self):
        self.sitemaps = {}

    def __iter__(self):
        self._generate_sitemaps_dict()
        return self.sitemaps.__iter__()

    def __getitem__(self, key):
        self._generate_sitemaps_dict()
        return self.sitemaps[key]

    def items(self):
        self._generate_sitemaps_dict()
        return self.sitemaps.items()

    def _generate_sitemaps_dict(self):
        if self.sitemaps:
            return
        for section in Section.objects.all():
            info_dict = {
                'queryset': section.article_set.filter(is_published=True),
            }
            # dict key is provided as 'section' in sitemap index view
            self.sitemaps[section.name] = GenericSitemap(info_dict, priority=0.6)



### urls.py
from sitemaps import SitemapLookup

...
...
...

sitemaps = SitemapLookup()

urlpatterns += patterns('',
        (r'^sitemap.xml
, 'django.contrib.sitemaps.views.index', {'sitemaps': sitemaps}),
        (r'^sitemap-(?P<section>.+)\.xml
, 'django.contrib.sitemaps.views.sitemap', {'sitemaps': sitemaps}),
)

For me, the accepted answer was impacting development and testing cycle speed since it made python manage.py commands run more slowly -- I had a little more to do in the DB than this example.

Here are the changes I made to mitigate (adapted to the example). Have yet to battle test it but this seems to do the trick (Python3):

### sitemaps.py

class SitemapLookup():
    """
    Instantiated class replaces the dictionary of {'sitemap-section': Sitemap} for urls.py
    Speeds up application load time by only querying the DB when a sitemap is first requested.
    """

    def __init__(self):
        self.sitemaps = {}

    def __iter__(self):
        self._generate_sitemaps_dict()
        return self.sitemaps.__iter__()

    def __getitem__(self, key):
        self._generate_sitemaps_dict()
        return self.sitemaps[key]

    def items(self):
        self._generate_sitemaps_dict()
        return self.sitemaps.items()

    def _generate_sitemaps_dict(self):
        if self.sitemaps:
            return
        for section in Section.objects.all():
            info_dict = {
                'queryset': section.article_set.filter(is_published=True),
            }
            # dict key is provided as 'section' in sitemap index view
            self.sitemaps[section.name] = GenericSitemap(info_dict, priority=0.6)



### urls.py
from sitemaps import SitemapLookup

...
...
...

sitemaps = SitemapLookup()

urlpatterns += patterns('',
        (r'^sitemap.xml
, 'django.contrib.sitemaps.views.index', {'sitemaps': sitemaps}),
        (r'^sitemap-(?P<section>.+)\.xml
, 'django.contrib.sitemaps.views.sitemap', {'sitemaps': sitemaps}),
)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文