Lastmod sitemap: sitemaps.org — Протокол – Добавляем в sitemap для Opencart 2.x — блог Окатьев.Ру

Добавляем в sitemap для Opencart 2.x — блог Окатьев.Ру

Или заставляем поисковых ботов проверять контент сайта чаще

Добавляем <lastmod> в sitemap для Opencart 2.x

Данный модуль добавляет в стоковый модуль генерации карты сайта для Opencart 2.x обязательную директиву , значение которой даёт поисковым роботам понять, когда последний раз изменилась та или иная запись в карте сайта, что очень важно для хорошей индексации твоего сайта.

Значение между тегами обновляется каждый раз при регенерации карты сайта и подставляет туда дату и время выполнения скрипта регенерации в нужном для поисковых роботов формате, например:

<lastmod>2017-07-20T23:34:44+00:00</lastmod>

Установка модуля

Модуль устанавливается как обычно, через стандартный установщик дополнений в админке — OCMOD и не заменяет никаких системных файлов и файлов шаблона. Скопируй код модуля в текстовый файл с названием lastmod.ocmod.xml и сохрани в любом месте, а затем загрузи его в установщик через админ-панель и после установки обнови кэш модификаторов (см. скриншоты выше).

Дополнение устанавливается на Opencart 2.0, Opencart 2.1, Opencart 2.2 и Opencart 2.3, а также на модифицированные движки ocStore 2.x.

Скачать архив с готовым файлом
<?xml version="1.0" encoding="UTF-8"?>
<modification>
<name>1Z realtime lastmod в Google и Yandex sitemaps [xml]</name>
<code>1Z realtime lastmod в Google и Yandex sitemaps [xml]</code>
<version>1.0</version>
<author>mrcivic</author>
<link>https://opencartforum.com/user/716269-mrcivic/</link>

<file path="catalog/controller/feed/google_sitemap.php">
	<operation error="skip">
	<search><![CDATA[$output .= '</url>';]]></search>
	<add position="before">
	<![CDATA[			$output .= '<lastmod>' . date('c',time()) . '</lastmod>';]]></add>
	</operation>
</file>

<file path="catalog/controller/feed/yandex_sitemap.php">
	<operation error="skip">
	<search><![CDATA[$output .= '</url>';]]></search>
	<add position="before">
	<![CDATA[			$output .= '<lastmod>' . date('c',time()) . '</lastmod>';]]></add>
	</operation>
</file>
</modification>

MODX - Создание sitemap | ИТ Шеф

Статья, в которой описывается процесс создания файла sitemap.xml, содержащего информацию о страницах веб-сайта, и его последующей регистрации в поисковых системах.

Файл sitemap.xml – это файл в формате XML, который составлен в соответствие с протоколом sitemap 0.9. Он предназначен для того, чтобы помочь поисковым системам (Яндекс, Google и Bing) проиндексировать страницы вашего сайта или блога. Данный файл, кроме адреса страницы (URL) содержит также ещё дополнительную информацию о каждой веб-странице: дату последней её модификации, насколько часто она изменяется и её приоритет перед другими страницами. Эту дополнительную информацию используют поисковые роботы, чтобы больше понять о каждой странице, а именно как часто надо ту или иную страницу заново индексировать, а также важность данной страницы перед другими страницами этого сайта или блога.

Для создания файла sitemap.xml будет использовать дополнение pdoTools, а точнее сниппет pdoSitemap. Данное дополнение (pdoTools) у нас уже установлено в MODX Revolution, так что можно сразу переходить к разработке карты сайта для поисковых систем.

1. Создать ресурс SiteMapXML и внести во вкладки "Документ" и "Настройки" следующие данные:

Вкладка "Документ":

  • Заголовок – SiteMapXML.
  • Шаблон – пустой.
  • Псевдоним – sitemap.
  • Не показывать в меню – Да.
  • Опубликован – Да.

MODX Revolution - Создание ресурса SiteMapXML. Вкладка - Документ.

Вкладка "Настройки":

  • Тип содержимого – XML.
  • Доступен для поиска – Нет.
  • Использовать HTML редактор – Нет.
  • Заморозить URI – Да.
  • URI – sitemap.xml.

MODX Revolution - Создание ресурса SiteMapXML. Вкладка - Настройки.

2. Сохранить ресурс SiteMapXML.

3. В поле содержимое ресурса SiteMapXML ввести следующее:


[[!pdoSitemap?
  &checkPermissions=`list`
]]

4. Проверяем результаты работы сниппета pdoSitemap. Для этого в адресной строке браузера вводим: http://www.mysite.ru/sitemap.xml.

MODX Revolution - Результаты работы сниппета pdoSitemap

5. Указать поисковым системам Яндекс, Google и Bing расположение карты сайта sitemap.xml.

Яндекс. В личном кабинете веб-мастера выбрать в левом меню пункт "Настройка индексирования" -> "Файлы Sitemap". В открывшейся форме ввести URL файла sitemap.xml и нажать на кнопку "Добавить".

Google. В личном кабинете веб-мастера в левом меню выбрать пункт "Сканирование" -> "Файлы Sitemap". В открывшейся странице нажать на кнопку "Добавление/Проверка файла sitemap".

Bing. В личном кабинете веб-мастера в левом меню выбрать пункт "Панель мониторинга" -> "Настройка сайта" -> "Sitemaps". В открывшейся странице указать URL файла sitemap.xml и нажать на кнопку "Отправить".

The sitemap framework — Документация Django 1.8

Django comes with a high-level sitemap-generating framework that makes creating sitemap XML files easy.

Overview

A sitemap is an XML file on your Web site that tells search-engine indexers how frequently your pages change and how “important” certain pages are in relation to other pages on your site. This information helps search engines index your site.

The Django sitemap framework automates the creation of this XML file by letting you express this information in Python code.

It works much like Django’s syndication framework. To create a sitemap, just write a Sitemap class and point to it in your URLconf.

Installation

To install the sitemap app, follow these steps:

  1. Add 'django.contrib.sitemaps' to your INSTALLED_APPS setting.
  2. Make sure your TEMPLATES setting contains a DjangoTemplates backend whose APP_DIRS options is set to True. It’s in there by default, so you’ll only need to change this if you’ve changed that setting.
  3. Make sure you’ve installed the sites framework.

(Note: The sitemap application doesn’t install any database tables. The only reason it needs to go into INSTALLED_APPS is so that the Loader() template loader can find the default templates.)

Initialization

views.sitemap(request, sitemaps, section=None, template_name='sitemap.xml', content_type='application/xml')

To activate sitemap generation on your Django site, add this line to your URLconf:

from django.contrib.sitemaps.views import sitemap

url(r'^sitemap\.xml$', sitemap, {'sitemaps': sitemaps},
    name='django.contrib.sitemaps.views.sitemap')

This tells Django to build a sitemap when a client accesses /sitemap.xml.

The name of the sitemap file is not important, but the location is. Search engines will only index links in your sitemap for the current URL level and below. For instance, if sitemap.xml lives in your root directory, it may reference any URL in your site. However, if your sitemap lives at /content/sitemap.xml, it may only reference URLs that begin with /content/.

The sitemap view takes an extra, required argument: {'sitemaps': sitemaps}. sitemaps should be a dictionary that maps a short section label (e.g., blog or news) to its Sitemap class (e.g., BlogSitemap or NewsSitemap). It may also map to an instance of a Sitemap class (e.g., BlogSitemap(some_var)).

Sitemap classes

A Sitemap class is a simple Python class that represents a “section” of entries in your sitemap. For example, one Sitemap class could represent all the entries of your Weblog, while another could represent all of the events in your events calendar.

In the simplest case, all these sections get lumped together into one sitemap.xml, but it’s also possible to use the framework to generate a sitemap index that references individual sitemap files, one per section. (See Creating a sitemap index below.)

Sitemap classes must subclass django.contrib.sitemaps.Sitemap. They can live anywhere in your codebase.

A simple example

Let’s assume you have a blog system, with an Entry model, and you want your sitemap to include all the links to your individual blog entries. Here’s how your sitemap class might look:

from django.contrib.sitemaps import Sitemap
from blog.models import Entry

class BlogSitemap(Sitemap):
    changefreq = "never"
    priority = 0.5

    def items(self):
        return Entry.objects.filter(is_draft=False)

    def lastmod(self, obj):
        return obj.pub_date

Note:

  • changefreq and priority are class attributes corresponding to <changefreq> and <priority> elements, respectively. They can be made callable as functions, as lastmod was in the example.
  • items() is simply a method that returns a list of objects. The objects returned will get passed to any callable methods corresponding to a sitemap property (location, lastmod, changefreq, and priority).
  • lastmod should return a Python datetime object.
  • There is no location method in this example, but you can provide it in order to specify the URL for your object. By default, location() calls get_absolute_url() on each object and returns the result.

Sitemap class reference

class Sitemap

A Sitemap class can define the following methods/attributes:

items

Required. A method that returns a list of objects. The framework doesn’t care what type of objects they are; all that matters is that these objects get passed to the location(), lastmod(), changefreq() and priority() methods.

location

Optional. Either a method or attribute.

If it’s a method, it should return the absolute path for a given object as returned by items().

If it’s an attribute, its value should be a string representing an absolute path to use for every object returned by items().

In both cases, “absolute path” means a URL that doesn’t include the protocol or domain. Examples:

  • Good: '/foo/bar/'
  • Bad: 'example.com/foo/bar/'
  • Bad: 'http://example.com/foo/bar/'

If location isn’t provided, the framework will call the get_absolute_url() method on each object as returned by items().

To specify a protocol other than 'http', use protocol.

lastmod

Optional. Either a method or attribute.

If it’s a method, it should take one argument – an object as returned by items() – and return that object’s last-modified date/time, as a Python datetime.datetime object.

If it’s an attribute, its value should be a Python datetime.datetime object representing the last-modified date/time for every object returned by items().

Добавлено в Django 1.7.

If all items in a sitemap have a lastmod, the sitemap generated by views.sitemap() will have a Last-Modified header equal to the latest lastmod. You can activate the ConditionalGetMiddleware to make Django respond appropriately to requests with an If-Modified-Since header which will prevent sending the sitemap if it hasn’t changed.

changefreq

Optional. Either a method or attribute.

If it’s a method, it should take one argument – an object as returned by items() – and return that object’s change frequency, as a Python string.

If it’s an attribute, its value should be a string representing the change frequency of every object returned by items().

Possible values for changefreq, whether you use a method or attribute, are:

  • 'always'
  • 'hourly'
  • 'daily'
  • 'weekly'
  • 'monthly'
  • 'yearly'
  • 'never'
priority

Optional. Either a method or attribute.

If it’s a method, it should take one argument – an object as returned by items() – and return that object’s priority, as either a string or float.

If it’s an attribute, its value should be either a string or float representing the priority of every object returned by items().

Example values for priority: 0.4, 1.0. The default priority of a page is 0.5. See the sitemaps.org documentation for more.

protocol

Optional.

This attribute defines the protocol ('http' or 'https') of the URLs in the sitemap. If it isn’t set, the protocol with which the sitemap was requested is used. If the sitemap is built outside the context of a request, the default is 'http'.

i18n

Добавлено в Django 1.8.

Optional.

A boolean attribute that defines if the URLs of this sitemap should be generated using all of your LANGUAGES. The default is False.

Shortcuts

The sitemap framework provides a couple convenience classes for common cases:

class FlatPageSitemap

The django.contrib.sitemaps.FlatPageSitemap class looks at all publicly visible flatpages defined for the current SITE_ID (see the sites documentation) and creates an entry in the sitemap. These entries include only the location attribute – not lastmod, changefreq or priority.

class GenericSitemap

The django.contrib.sitemaps.GenericSitemap class allows you to create a sitemap by passing it a dictionary which has to contain at least a queryset entry. This queryset will be used to generate the items of the sitemap. It may also have a date_field entry that specifies a date field for objects retrieved from the queryset. This will be used for the lastmod attribute in the generated sitemap. You may also pass priority and changefreq keyword arguments to the GenericSitemap constructor to specify these attributes for all URLs.

Example

Here’s an example of a URLconf using GenericSitemap:

from django.conf.urls import url
from django.contrib.sitemaps import GenericSitemap
from django.contrib.sitemaps.views import sitemap
from blog.models import Entry

info_dict = {
    'queryset': Entry.objects.all(),
    'date_field': 'pub_date',
}

urlpatterns = [
    # some generic view using info_dict
    # ...

    # the sitemap
    url(r'^sitemap\.xml$', sitemap,
        {'sitemaps': {'blog': GenericSitemap(info_dict, priority=0.6)}},
        name='django.contrib.sitemaps.views.sitemap'),
]

Sitemap for static views

Often you want the search engine crawlers to index views which are neither object detail pages nor flatpages. The solution is to explicitly list URL names for these views in items and call reverse() in the location method of the sitemap. For example:

# sitemaps.py
from django.contrib import sitemaps
from django.core.urlresolvers import reverse

class StaticViewSitemap(sitemaps.Sitemap):
    priority = 0.5
    changefreq = 'daily'

    def items(self):
        return ['main', 'about', 'license']

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

# urls.py
from django.conf.urls import url
from django.contrib.sitemaps.views import sitemap

from .sitemaps import StaticViewSitemap
from . import views

sitemaps = {
    'static': StaticViewSitemap,
}

urlpatterns = [
    url(r'^$', views.main, name='main'),
    url(r'^about/$', views.about, name='about'),
    url(r'^license/$', views.license, name='license'),
    # ...
    url(r'^sitemap\.xml$', sitemap, {'sitemaps': sitemaps},
        name='django.contrib.sitemaps.views.sitemap')
]

Creating a sitemap index

views.index(request, sitemaps, template_name='sitemap_index.xml', content_type='application/xml', sitemap_url_name='django.contrib.sitemaps.views.sitemap')

The sitemap framework also has the ability to create a sitemap index that references individual sitemap files, one per each section defined in your sitemaps dictionary. The only differences in usage are:

Here’s what the relevant URLconf lines would look like for the example above:

from django.contrib.sitemaps import views

urlpatterns = [
    url(r'^sitemap\.xml$', views.index, {'sitemaps': sitemaps}),
    url(r'^sitemap-(?P<section>.+)\.xml$', views.sitemap, {'sitemaps': sitemaps}),
]

This will automatically generate a sitemap.xml file that references both sitemap-flatpages.xml and sitemap-blog.xml. The Sitemap classes and the sitemaps dict don’t change at all.

You should create an index file if one of your sitemaps has more than 50,000 URLs. In this case, Django will automatically paginate the sitemap, and the index will reflect that.

If you’re not using the vanilla sitemap view – for example, if it’s wrapped with a caching decorator – you must name your sitemap view and pass sitemap_url_name to the index view:

from django.contrib.sitemaps import views as sitemaps_views
from django.views.decorators.cache import cache_page

urlpatterns = [
    url(r'^sitemap\.xml$',
        cache_page(86400)(sitemaps_views.index),
        {'sitemaps': sitemaps, 'sitemap_url_name': 'sitemaps'}),
    url(r'^sitemap-(?P<section>.+)\.xml$',
        cache_page(86400)(sitemaps_views.sitemap),
        {'sitemaps': sitemaps}, name='sitemaps'),
]

Template customization

If you wish to use a different template for each sitemap or sitemap index available on your site, you may specify it by passing a template_name parameter to the sitemap and index views via the URLconf:

from django.contrib.sitemaps import views

urlpatterns = [
    url(r'^custom-sitemap\.xml$', views.index, {
        'sitemaps': sitemaps,
        'template_name': 'custom_sitemap.html'
    }),
    url(r'^custom-sitemap-(?P<section>.+)\.xml$', views.sitemap, {
        'sitemaps': sitemaps,
        'template_name': 'custom_sitemap.html'
    }),
]

These views return TemplateResponse instances which allow you to easily customize the response data before rendering. For more details, see the TemplateResponse documentation.

Context variables

When customizing the templates for the index() and sitemap() views, you can rely on the following context variables.

Index

The variable sitemaps is a list of absolute URLs to each of the sitemaps.

Sitemap

The variable urlset is a list of URLs that should appear in the sitemap. Each URL exposes attributes as defined in the Sitemap class:

  • changefreq
  • item
  • lastmod
  • location
  • priority

The item attribute has been added for each URL to allow more flexible customization of the templates, such as Google news sitemaps. Assuming Sitemap’s items() would return a list of items with publication_data and a tags field something like this would generate a Google News compatible sitemap:

<?xml version="1.0" encoding="UTF-8"?>
<urlset
  xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
  xmlns:news="http://www.google.com/schemas/sitemap-news/0.9">
{% spaceless %}
{% for url in urlset %}
  <url>
    <loc>{{ url.location }}</loc>
    {% if url.lastmod %}<lastmod>{{ url.lastmod|date:"Y-m-d" }}</lastmod>{% endif %}
    {% if url.changefreq %}<changefreq>{{ url.changefreq }}</changefreq>{% endif %}
    {% if url.priority %}<priority>{{ url.priority }}</priority>{% endif %}
    <news:news>
      {% if url.item.publication_date %}<news:publication_date>{{ url.item.publication_date|date:"Y-m-d" }}</news:publication_date>{% endif %}
      {% if url.item.tags %}<news:keywords>{{ url.item.tags }}</news:keywords>{% endif %}
    </news:news>
   </url>
{% endfor %}
{% endspaceless %}
</urlset>

Pinging Google

You may want to “ping” Google when your sitemap changes, to let it know to reindex your site. The sitemaps framework provides a function to do just that: django.contrib.sitemaps.ping_google().

ping_google()

ping_google() takes an optional argument, sitemap_url, which should be the absolute path to your site’s sitemap (e.g., '/sitemap.xml'). If this argument isn’t provided, ping_google() will attempt to figure out your sitemap by performing a reverse looking in your URLconf.

ping_google() raises the exception django.contrib.sitemaps.SitemapNotFound if it cannot determine your sitemap URL.

One useful way to call ping_google() is from a model’s save() method:

from django.contrib.sitemaps import ping_google

class Entry(models.Model):
    # ...
    def save(self, force_insert=False, force_update=False):
        super(Entry, self).save(force_insert, force_update)
        try:
            ping_google()
        except Exception:
            # Bare 'except' because we could get a variety
            # of HTTP-related exceptions.
            pass

A more efficient solution, however, would be to call ping_google() from a cron script, or some other scheduled task. The function makes an HTTP request to Google’s servers, so you may not want to introduce that network overhead each time you call save().

Pinging Google via manage.py

django-admin ping_google

Once the sitemaps application is added to your project, you may also ping Google using the ping_google management command:

python manage.py ping_google [/sitemap.xml]

MODX sitemap или как в MODX Revo создать sitemap.xml

Автор Алексей На чтение 2 мин. Опубликовано

Последнее изменение поста: 23 октября 2018 в 23:30

Сегодня мы разберем как в MODX Revo создать sitemap.xml. Перед тем как начать, давайте изучим немного теории.

Что такое sitemap.xml

Sitemaps — это XML файл содержащий в себе информацию для роботов поисковых систем, о страницах сайта, подлежащих индексации. Иными словами сайтмап помогает поисковым роботам более быстро определять место нахождения страниц, время и частоту их обновления, а так же их важность.

Создание sitemap.xml в MODX Revo

Перед тем как начать, вам желательно настроить чпу modx, если оно не настроено.

Создавать sitemap.xml мы будем при помощи pdoSitemap (данный сниппет входит в пакет pdoTools), он у вас должен быть уже установлен. Рассмотрим по шагово, процесс создания сайтмап.

1. Создайте документ и заполните вкладку «Документ» следующим образом:

  • Заголовок – sitemap;
  • Шаблон – пустой шаблон;
  • Псевдоним – sitemap;
  • Не показывать в меню – Да.
  • Опубликован – Да.

Создание sitemap вкладка Настройки

2. Перейдите во вкладку «Настройки» и выберите следующее:

  • Тип содержимого – XML.
  • Доступен для поиска – Нет.
  • Использовать HTML редактор – Нет.
  • Сохранить документ (ресурс).

Примечание! Если у вас не настроено ЧПУ, то во вкладке Настройки вероятно нужно так же выбрать — Заморозить URI и ввести в поле URL — sitemap.xml.

Создание sitemap вкладка Настройки

3. В поле содержимое ввести: [[!pdoSitemap]] и снова сохранить.

Сохраняем и смотрим результат

Все. Можно проверить результат, для того нажмите на кнопку посмотреть, либо перейдите по адресу сайт.ru/sitemap.xml.

The sitemap framework — Документация Django 1.4

Django comes with a high-level sitemap-generating framework that makes creating sitemap XML files easy.

Overview

A sitemap is an XML file on your Web site that tells search-engine indexers how frequently your pages change and how “important” certain pages are in relation to other pages on your site. This information helps search engines index your site.

The Django sitemap framework automates the creation of this XML file by letting you express this information in Python code.

It works much like Django’s syndication framework. To create a sitemap, just write a Sitemap class and point to it in your URLconf.

Installation

To install the sitemap app, follow these steps:

  1. Add 'django.contrib.sitemaps' to your INSTALLED_APPS setting.
  2. Make sure 'django.template.loaders.app_directories.Loader' is in your TEMPLATE_LOADERS setting. It’s in there by default, so you’ll only need to change this if you’ve changed that setting.
  3. Make sure you’ve installed the sites framework.

(Note: The sitemap application doesn’t install any database tables. The only reason it needs to go into INSTALLED_APPS is so that the Loader() template loader can find the default templates.)

Initialization

To activate sitemap generation on your Django site, add this line to your URLconf:

(r'^sitemap\.xml$', 'django.contrib.sitemaps.views.sitemap', {'sitemaps': sitemaps})

This tells Django to build a sitemap when a client accesses /sitemap.xml.

The name of the sitemap file is not important, but the location is. Search engines will only index links in your sitemap for the current URL level and below. For instance, if sitemap.xml lives in your root directory, it may reference any URL in your site. However, if your sitemap lives at /content/sitemap.xml, it may only reference URLs that begin with /content/.

The sitemap view takes an extra, required argument: {'sitemaps': sitemaps}. sitemaps should be a dictionary that maps a short section label (e.g., blog or news) to its Sitemap class (e.g., BlogSitemap or NewsSitemap). It may also map to an instance of a Sitemap class (e.g., BlogSitemap(some_var)).

Sitemap classes

A Sitemap class is a simple Python class that represents a “section” of entries in your sitemap. For example, one Sitemap class could represent all the entries of your Weblog, while another could represent all of the events in your events calendar.

In the simplest case, all these sections get lumped together into one sitemap.xml, but it’s also possible to use the framework to generate a sitemap index that references individual sitemap files, one per section. (See Creating a sitemap index below.)

Sitemap classes must subclass django.contrib.sitemaps.Sitemap. They can live anywhere in your codebase.

A simple example

Let’s assume you have a blog system, with an Entry model, and you want your sitemap to include all the links to your individual blog entries. Here’s how your sitemap class might look:

from django.contrib.sitemaps import Sitemap
from blog.models import Entry

class BlogSitemap(Sitemap):
    changefreq = "never"
    priority = 0.5

    def items(self):
        return Entry.objects.filter(is_draft=False)

    def lastmod(self, obj):
        return obj.pub_date

Note:

  • changefreq and priority are class attributes corresponding to <changefreq> and <priority> elements, respectively. They can be made callable as functions, as lastmod was in the example.
  • items() is simply a method that returns a list of objects. The objects returned will get passed to any callable methods corresponding to a sitemap property (location, lastmod, changefreq, and priority).
  • lastmod should return a Python datetime object.
  • There is no location method in this example, but you can provide it in order to specify the URL for your object. By default, location() calls get_absolute_url() on each object and returns the result.

Sitemap class reference

class Sitemap

A Sitemap class can define the following methods/attributes:

items

Required. A method that returns a list of objects. The framework doesn’t care what type of objects they are; all that matters is that these objects get passed to the location(), lastmod(), changefreq() and priority() methods.

location

Optional. Either a method or attribute.

If it’s a method, it should return the absolute path for a given object as returned by items().

If it’s an attribute, its value should be a string representing an absolute path to use for every object returned by items().

In both cases, “absolute path” means a URL that doesn’t include the protocol or domain. Examples:

  • Good: '/foo/bar/'
  • Bad: 'example.com/foo/bar/'
  • Bad: 'http://example.com/foo/bar/'

If location isn’t provided, the framework will call the get_absolute_url() method on each object as returned by items().

To specify a protocol other than 'http', use protocol.

lastmod

Optional. Either a method or attribute.

If it’s a method, it should take one argument – an object as returned by items() – and return that object’s last-modified date/time, as a Python datetime.datetime object.

If it’s an attribute, its value should be a Python datetime.datetime object representing the last-modified date/time for every object returned by items().

changefreq

Optional. Either a method or attribute.

If it’s a method, it should take one argument – an object as returned by items() – and return that object’s change frequency, as a Python string.

If it’s an attribute, its value should be a string representing the change frequency of every object returned by items().

Possible values for changefreq, whether you use a method or attribute, are:

  • 'always'
  • 'hourly'
  • 'daily'
  • 'weekly'
  • 'monthly'
  • 'yearly'
  • 'never'
priority

Optional. Either a method or attribute.

If it’s a method, it should take one argument – an object as returned by items() – and return that object’s priority, as either a string or float.

If it’s an attribute, its value should be either a string or float representing the priority of every object returned by items().

Example values for priority: 0.4, 1.0. The default priority of a page is 0.5. See the sitemaps.org documentation for more.

protocol

Добавлено в Django 1.4.

Optional.

This attribute defines the protocol ('http' or 'https') of the URLs in the sitemap. If it isn’t set, the protocol with which the sitemap was requested is used. If the sitemap is built outside the context of a request, the default is 'http'.

Shortcuts

The sitemap framework provides a couple convenience classes for common cases:

class FlatPageSitemap

The django.contrib.sitemaps.FlatPageSitemap class looks at all publicly visible flatpages defined for the current SITE_ID (see the sites documentation) and creates an entry in the sitemap. These entries include only the location attribute – not lastmod, changefreq or priority.

class GenericSitemap

The django.contrib.sitemaps.GenericSitemap class works with any generic views you already have. To use it, create an instance, passing in the same info_dict you pass to the generic views. The only requirement is that the dictionary have a queryset entry. It may also have a date_field entry that specifies a date field for objects retrieved from the queryset. This will be used for the lastmod attribute in the generated sitemap. You may also pass priority and changefreq keyword arguments to the GenericSitemap constructor to specify these attributes for all URLs.

Example

Here’s an example of a URLconf using both:

from django.conf.urls import patterns, url, include
from django.contrib.sitemaps import FlatPageSitemap, GenericSitemap
from blog.models import Entry

info_dict = {
    'queryset': Entry.objects.all(),
    'date_field': 'pub_date',
}

sitemaps = {
    'flatpages': FlatPageSitemap,
    'blog': GenericSitemap(info_dict, priority=0.6),
}

urlpatterns = patterns('',
    # some generic view using info_dict
    # ...

    # the sitemap
    (r'^sitemap\.xml$', 'django.contrib.sitemaps.views.sitemap', {'sitemaps': sitemaps})
)

Creating a sitemap index

The sitemap framework also has the ability to create a sitemap index that references individual sitemap files, one per each section defined in your sitemaps dictionary. The only differences in usage are:

  • You use two views in your URLconf: django.contrib.sitemaps.views.index() and django.contrib.sitemaps.views.sitemap().
  • The django.contrib.sitemaps.views.sitemap() view should take a section keyword argument.

Here’s what the relevant URLconf lines would look like for the example above:

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

This will automatically generate a sitemap.xml file that references both sitemap-flatpages.xml and sitemap-blog.xml. The Sitemap classes and the sitemaps dict don’t change at all.

You should create an index file if one of your sitemaps has more than 50,000 URLs. In this case, Django will automatically paginate the sitemap, and the index will reflect that.

Добавлено в Django 1.4.

If you’re not using the vanilla sitemap view – for example, if it’s wrapped with a caching decorator – you must name your sitemap view and pass sitemap_url_name to the index view:

from django.contrib.sitemaps import views as sitemaps_views
from django.views.decorators.cache import cache_page

urlpatterns = patterns('',
    url(r'^sitemap.xml$',
        cache_page(86400)(sitemaps_views.index),
        {'sitemaps': sitemaps, 'sitemap_url_name': 'sitemaps'}),
    url(r'^sitemap-(?P<section>.+)\.xml$',
        cache_page(86400)(sitemaps_views.sitemap),
        {'sitemaps': sitemaps}, name='sitemaps'),
)

Template customization

Добавлено в Django 1.3.

If you wish to use a different template for each sitemap or sitemap index available on your site, you may specify it by passing a template_name parameter to the sitemap and index views via the URLconf:

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

Context variables

When customizing the templates for the index() and sitemaps() views, you can rely on the following context variables.

Index

The variable sitemaps is a list of absolute URLs to each of the sitemaps.

Sitemap

The variable urlset is a list of URLs that should appear in the sitemap. Each URL exposes attributes as defined in the Sitemap class:

  • changefreq
  • item
  • lastmod
  • location
  • priority

Добавлено в Django 1.4.

The item attribute has been added for each URL to allow more flexible customization of the templates, such as Google news sitemaps. Assuming Sitemap’s items() would return a list of items with publication_data and a tags field something like this would generate a Google News compatible sitemap:

<?xml version="1.0" encoding="UTF-8"?>
<urlset
  xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
  xmlns:news="http://www.google.com/schemas/sitemap-news/0.9">
{% spaceless %}
{% for url in urlset %}
  <url>
    <loc>{{ url.location }}</loc>
    {% if url.lastmod %}<lastmod>{{ url.lastmod|date:"Y-m-d" }}</lastmod>{% endif %}
    {% if url.changefreq %}<changefreq>{{ url.changefreq }}</changefreq>{% endif %}
    {% if url.priority %}<priority>{{ url.priority }}</priority>{% endif %}
    <news:news>
      {% if url.item.publication_date %}<news:publication_date>{{ url.item.publication_date|date:"Y-m-d" }}</news:publication_date>{% endif %}
      {% if url.item.tags %}<news:keywords>{{ url.item.tags }}</news:keywords>{% endif %}
    </news:news>
   </url>
{% endfor %}
{% endspaceless %}
</urlset>

Pinging Google

You may want to “ping” Google when your sitemap changes, to let it know to reindex your site. The sitemaps framework provides a function to do just that: django.contrib.sitemaps.ping_google().

ping_google()

ping_google() takes an optional argument, sitemap_url, which should be the absolute path to your site’s sitemap (e.g., '/sitemap.xml'). If this argument isn’t provided, ping_google() will attempt to figure out your sitemap by performing a reverse looking in your URLconf.

ping_google() raises the exception django.contrib.sitemaps.SitemapNotFound if it cannot determine your sitemap URL.

One useful way to call ping_google() is from a model’s save() method:

from django.contrib.sitemaps import ping_google

 class Entry(models.Model):
     # ...
     def save(self, force_insert=False, force_update=False):
         super(Entry, self).save(force_insert, force_update)
         try:
             ping_google()
         except Exception:
             # Bare 'except' because we could get a variety
             # of HTTP-related exceptions.
             pass

A more efficient solution, however, would be to call ping_google() from a cron script, or some other scheduled task. The function makes an HTTP request to Google’s servers, so you may not want to introduce that network overhead each time you call save().

Pinging Google via manage.py

django-admin.py ping_google

Once the sitemaps application is added to your project, you may also ping Google using the ping_google management command:

python manage.py ping_google [/sitemap.xml]

Отправить ответ

avatar
  Подписаться  
Уведомление о