Spec-Zone.ru › Django 1.8

Структура фреймворка для фидов синдикации

Django поставляется с фреймворком высокого уровня для генерации фидов синдикации, который упрощает создание фидов RSS и Atom.

Для создания любого фида синдикации вам нужно написать небольшой класс Python. Вы можете создавать сколько угодно фидов.

Django также поставляет API для генерации фидов низкого уровня. Используйте его, если хотите генерировать фиды вне веб-контекста или иным низкоуровневым способом.

Фреймворк высокого уровня

Обзор

Фреймворк высокого уровня для генерации фидов предоставляется классом Feed. Для создания фида напишите класс Feed и укажите на его экземпляр в вашей конфигурации URL.

Классы фидов

Класс Feed — это класс Python, представляющий собой фид синдикации. Фид может быть простым (например, «фид новостей сайта» или базовый фид, отображающий последние записи блога) или более сложным (например, фид, отображающий все записи блога в определённой категории, где категория изменяется).

Классы фидов наследуются от django.contrib.syndication.views.Feed. Они могут располагаться в любом месте вашего кода.

Экземпляры классов Feed являются представлениями, которые могут использоваться в вашей конфигурации URL.

Простой пример

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

from django.contrib.syndication.views import Feed
from django.core.urlresolvers import reverse
from policebeat.models import NewsItem

class LatestEntriesFeed(Feed):
    title = "Police beat site news"
    link = "/sitenews/"
    description = "Updates on changes and additions to police beat central."

    def items(self):
        return NewsItem.objects.order_by('-pub_date')[:5]

    def item_title(self, item):
        return item.title

    def item_description(self, item):
        return item.description

    # item_link is only needed if NewsItem has no get_absolute_url method.
    def item_link(self, item):
        return reverse('news-item', args=[item.pk])

Чтобы связать URL с этим фидом, поместите экземпляр объекта Feed в вашу конфигурацию URL. Например:

from django.conf.urls import url
from myproject.feeds import LatestEntriesFeed

urlpatterns = [
    # ...
    url(r'^latest/feed/$', LatestEntriesFeed()),
    # ...
]

Примечание:

  • Класс Feed наследуется от django.contrib.syndication.views.Feed.
  • title, link и description соответствуют стандартным элементам RSS <title>, <link> и <description> соответственно.
  • items() — это просто метод, который возвращает список объектов, которые должны быть включены в фид в качестве <item> элементов. Хотя в этом примере возвращаются объекты NewsItem с помощью объектно-реляционного маппера Django, items() не обязан возвращать экземпляры моделей. Хотя вы получаете несколько функций «бесплатно», используя модели Django, items() может возвращать любые объекты, которые вы хотите.
  • Если вы создаёте фид Atom, а не RSS, установите атрибут subtitle вместо атрибута description. См. Публикация фидов Atom и RSS совместно ниже для примера.

Осталось сделать одно. В фиде RSS каждый <item> имеет <title>, <link> и <description>. Нам нужно сказать фреймворку, какие данные поместить в эти элементы.

  • Для содержимого <title> и <description> Django пытается вызвать методы item_title() и item_description() в классе Feed. Им передаётся единственный параметр, item, который является самим объектом. Эти методы являются необязательными; по умолчанию используется строковое представление объекта для обоих.

    Если вам нужно выполнить специальное форматирование заголовка или описания, можно использовать шаблоны Django вместо этого. Их пути можно указать с помощью атрибутов title_template и description_template в классе Feed. Шаблоны рендерятся для каждого элемента и получают две переменные контекста шаблона:

    • {{ obj }} — текущий объект (один из объектов, которые вы вернули в items()).
    • {{ site }} — объект django.contrib.sites.models.Site, представляющий текущий сайт. Это полезно для {{ site.domain }} или {{ site.name }} При отсутствии фреймворка сайтов Django этот объект будет иметь тип RequestSite. См. раздел RequestSite в документации фреймворка сайтов для получения более подробной информации.

    См. сложный пример ниже, который использует шаблон описания.

    Feed.get_context_data(**kwargs)

    Также существует способ передачи дополнительной информации в шаблоны заголовков и описаний, если вам нужно предоставить больше, чем две указанные выше переменные. Вы можете реализовать метод get_context_data в подклассе Feed. Например:

    from mysite.models import Article
    from django.contrib.syndication.views import Feed
    
    class ArticlesFeed(Feed):
        title = "My articles"
        description_template = "feeds/articles.html"
    
        def items(self):
            return Article.objects.order_by('-pub_date')[:5]
    
        def get_context_data(self, **kwargs):
            context = super(ArticlesFeed, self).get_context_data(**kwargs)
            context['foo'] = 'bar'
            return context
    

    И шаблон:

    Something about {{ foo }}: {{ obj.description }}
    

    Этот метод вызывается один раз для каждого элемента в списке, возвращённом методом items(), со следующими ключевыми аргументами:

    • item: текущий элемент. Для обратной совместимости имя этой переменной контекста — {{ obj }}.
    • obj: объект, возвращённый методом get_object(). По умолчанию он не отображается в шаблонах, чтобы избежать путаницы с {{ obj }} (см. выше), но вы можете использовать его в реализации метода get_context_data().
    • site: текущий сайт, как описано выше.
    • request: текущий запрос.

    Поведение метода get_context_data() аналогично поведению представлений общих видов — вы должны вызвать метод super() для получения данных контекста из родительского класса, добавить свои данные и вернуть изменённый словарь.

  • Для указания содержимого <link> у вас есть два варианта. Для каждого элемента в items() Django сначала пытается вызвать метод item_link() в классе Feed. Так же, как и с заголовком и описанием, ему передаётся единственный параметр, item. Если этот метод не существует, Django пытается выполнить метод get_absolute_url() на этом объекте. Методы get_absolute_url() и item_link() должны возвращать URL элемента в виде обычной строки Python. Как и с get_absolute_url(), результат item_link() будет включён непосредственно в URL, поэтому вы несёте ответственность за выполнение всех необходимых операций URL-кодирования и преобразования в ASCII в самом методе.

Сложный пример

Фреймворк также поддерживает более сложные фиды с помощью аргументов.

Например, веб-сайт может предложить фид RSS последних преступлений для каждого полицейского участка в городе. Было бы глупо создавать отдельный класс Feed для каждого полицейского участка; это нарушит принцип DRY и свяжет данные с логикой программирования. Вместо этого фреймворк синдикации позволяет получить доступ к аргументам, переданным из вашей конфигурации URL, чтобы фиды могли выводить элементы на основе информации в URL фида.

Фиды полицейских участков могут быть доступны по таким URL:

  • /beats/613/rss/ — возвращает последние преступления для участка 613.
  • /beats/1424/rss/ — возвращает последние преступления для участка 1424.

Они могут быть сопоставлены с такой строкой в конфигурации URL:

url(r'^beats/(?P<beat_id>[0-9]+)/rss/$', BeatFeed()),

Как и в представлении, аргументы в URL передаются в метод get_object() вместе с объектом запроса.

Вот код для этих фидов, специфичных для участков:

from django.contrib.syndication.views import Feed

class BeatFeed(Feed):
    description_template = 'feeds/beat_description.html'

    def get_object(self, request, beat_id):
        return Beat.objects.get(pk=beat_id)

    def title(self, obj):
        return "Police beat central: Crimes for beat %s" % obj.beat

    def link(self, obj):
        return obj.get_absolute_url()

    def description(self, obj):
        return "Crimes recently reported in police beat %s" % obj.beat

    def items(self, obj):
        return Crime.objects.filter(beat=obj).order_by('-crime_date')[:30]

Для генерации <title>, <link> и <description> фида Django использует методы title(), link() и description() Соответственно. В предыдущем примере они были простыми строковыми атрибутами класса, но этот пример показывает, что они могут быть либо строками, либо методами. Для каждого из title, link и description Django выполняет следующий алгоритм:

  • Сначала пытается вызвать метод, передав аргумент obj, где obj — объект, возвращённый методом get_object().
  • Если это не удаётся, пытается вызвать метод без аргументов.
  • Если и это не удаётся, использует атрибут класса.

Также обратите внимание, что items() также следует тому же алгоритму — сначала пытается вызвать items(obj), затем items(), и наконец использует атрибут класса items (который должен быть списком).

Мы используем шаблон для описаний элементов. Он может быть очень простым:

{{ obj.description }}

Однако вы можете добавлять форматирование по своему усмотрению.

Класс ExampleFeed ниже предоставляет полную документацию по методам и атрибутам классов Feed.

Указание типа ленты

По умолчанию ленты, созданные в этой системе, используют RSS 2.0.

Чтобы изменить это, добавьте атрибут feed_type к вашему классу Feed, как показано ниже:

from django.utils.feedgenerator import Atom1Feed

class MyFeed(Feed):
    feed_type = Atom1Feed

Обратите внимание, что вы задаёте feed_type объект класса, а не экземпляр.

В настоящее время доступны следующие типы лент:

  • django.utils.feedgenerator.Rss201rev2Feed (RSS 2.01. По умолчанию.)
  • django.utils.feedgenerator.RssUserland091Feed (RSS 0.91.)
  • django.utils.feedgenerator.Atom1Feed (Atom 1.0.)

Вложения

Для указания вложений, таких как те, которые используются при создании лент подкастов, используйте методы item_enclosure_url, item_enclosure_length и item_enclosure_mime_type. См. примеры использования в классе ExampleFeed ниже.

Язык

Ленты, созданные системой агрегации, автоматически включают соответствующий тег <language> (RSS 2.0) или атрибут xml:lang (Atom). Он берётся непосредственно из вашего параметра LANGUAGE_CODE.

URL-адреса

Метод/атрибут link может возвращать либо абсолютный путь (например, "/blog/"), либо URL-адрес с полным доменным именем и протоколом (например, "http://www.example.com/blog/"). Если link не возвращает домен, система агрегации вставит домен текущего сайта в соответствии с вашим параметром SITE_ID setting.

Для Atom-лент требуется <link rel="self">, который определяет текущее расположение ленты. Система агрегации заполняет его автоматически, используя домен текущего сайта в соответствии с параметром SITE_ID.

Публикация Atom и RSS лент одновременно

Некоторые разработчики предпочитают предоставлять как Atom, так и RSS версии своих лент. Это легко сделать с Django: просто создайте подкласс своего класса Feed и задайте feed_type на другое значение. Затем обновите свой URLconf, чтобы добавить дополнительные версии.

Вот полный пример:

from django.contrib.syndication.views import Feed
from policebeat.models import NewsItem
from django.utils.feedgenerator import Atom1Feed

class RssSiteNewsFeed(Feed):
    title = "Police beat site news"
    link = "/sitenews/"
    description = "Updates on changes and additions to police beat central."

    def items(self):
        return NewsItem.objects.order_by('-pub_date')[:5]

class AtomSiteNewsFeed(RssSiteNewsFeed):
    feed_type = Atom1Feed
    subtitle = RssSiteNewsFeed.description

Примечание

В этом примере RSS-лента использует description, а Atom-лента использует subtitle. Это связано с тем, что Atom-ленты не поддерживают «описание» на уровне ленты, но поддерживают «подзаголовок».

Если вы укажете description в своём классе Feed, Django не автоматически добавит его в элемент subtitle, так как подзаголовок и описание не всегда одно и то же. Вместо этого вы должны определить атрибут subtitle.

В приведённом выше примере мы просто задали атрибут subtitle Atom-ленты равным description RSS-ленты, потому что он уже довольно короткий.

А соответствующий URLconf:

from django.conf.urls import url
from myproject.feeds import RssSiteNewsFeed, AtomSiteNewsFeed

urlpatterns = [
    # ...
    url(r'^sitenews/rss/$', RssSiteNewsFeed()),
    url(r'^sitenews/atom/$', AtomSiteNewsFeed()),
    # ...
]

Справочник по классу ленты

class views.Feed

Этот пример иллюстрирует все возможные атрибуты и методы класса Feed:

from django.contrib.syndication.views import Feed
from django.utils import feedgenerator

class ExampleFeed(Feed):

    # FEED TYPE -- Optional. This should be a class that subclasses
    # django.utils.feedgenerator.SyndicationFeed. This designates
    # which type of feed this should be: RSS 2.0, Atom 1.0, etc. If
    # you don't specify feed_type, your feed will be RSS 2.0. This
    # should be a class, not an instance of the class.

    feed_type = feedgenerator.Rss201rev2Feed

    # TEMPLATE NAMES -- Optional. These should be strings
    # representing names of Django templates that the system should
    # use in rendering the title and description of your feed items.
    # Both are optional. If a template is not specified, the
    # item_title() or item_description() methods are used instead.

    title_template = None
    description_template = None

    # TITLE -- One of the following three is required. The framework
    # looks for them in this order.

    def title(self, obj):
        """
        Takes the object returned by get_object() and returns the
        feed's title as a normal Python string.
        """

    def title(self):
        """
        Returns the feed's title as a normal Python string.
        """

    title = 'foo' # Hard-coded title.

    # LINK -- One of the following three is required. The framework
    # looks for them in this order.

    def link(self, obj):
        """
        # Takes the object returned by get_object() and returns the URL
        # of the HTML version of the feed as a normal Python string.
        """

    def link(self):
        """
        Returns the URL of the HTML version of the feed as a normal Python
        string.
        """

    link = '/blog/' # Hard-coded URL.

    # FEED_URL -- One of the following three is optional. The framework
    # looks for them in this order.

    def feed_url(self, obj):
        """
        # Takes the object returned by get_object() and returns the feed's
        # own URL as a normal Python string.
        """

    def feed_url(self):
        """
        Returns the feed's own URL as a normal Python string.
        """

    feed_url = '/blog/rss/' # Hard-coded URL.

    # GUID -- One of the following three is optional. The framework looks
    # for them in this order. This property is only used for Atom feeds
    # (where it is the feed-level ID element). If not provided, the feed
    # link is used as the ID.

    def feed_guid(self, obj):
        """
        Takes the object returned by get_object() and returns the globally
        unique ID for the feed as a normal Python string.
        """

    def feed_guid(self):
        """
        Returns the feed's globally unique ID as a normal Python string.
        """

    feed_guid = '/foo/bar/1234' # Hard-coded guid.

    # DESCRIPTION -- One of the following three is required. The framework
    # looks for them in this order.

    def description(self, obj):
        """
        Takes the object returned by get_object() and returns the feed's
        description as a normal Python string.
        """

    def description(self):
        """
        Returns the feed's description as a normal Python string.
        """

    description = 'Foo bar baz.' # Hard-coded description.

    # AUTHOR NAME --One of the following three is optional. The framework
    # looks for them in this order.

    def author_name(self, obj):
        """
        Takes the object returned by get_object() and returns the feed's
        author's name as a normal Python string.
        """

    def author_name(self):
        """
        Returns the feed's author's name as a normal Python string.
        """

    author_name = 'Sally Smith' # Hard-coded author name.

    # AUTHOR EMAIL --One of the following three is optional. The framework
    # looks for them in this order.

    def author_email(self, obj):
        """
        Takes the object returned by get_object() and returns the feed's
        author's email as a normal Python string.
        """

    def author_email(self):
        """
        Returns the feed's author's email as a normal Python string.
        """

    author_email = 'test@example.com' # Hard-coded author email.

    # AUTHOR LINK --One of the following three is optional. The framework
    # looks for them in this order. In each case, the URL should include
    # the "http://" and domain name.

    def author_link(self, obj):
        """
        Takes the object returned by get_object() and returns the feed's
        author's URL as a normal Python string.
        """

    def author_link(self):
        """
        Returns the feed's author's URL as a normal Python string.
        """

    author_link = 'http://www.example.com/' # Hard-coded author URL.

    # CATEGORIES -- One of the following three is optional. The framework
    # looks for them in this order. In each case, the method/attribute
    # should return an iterable object that returns strings.

    def categories(self, obj):
        """
        Takes the object returned by get_object() and returns the feed's
        categories as iterable over strings.
        """

    def categories(self):
        """
        Returns the feed's categories as iterable over strings.
        """

    categories = ("python", "django") # Hard-coded list of categories.

    # COPYRIGHT NOTICE -- One of the following three is optional. The
    # framework looks for them in this order.

    def feed_copyright(self, obj):
        """
        Takes the object returned by get_object() and returns the feed's
        copyright notice as a normal Python string.
        """

    def feed_copyright(self):
        """
        Returns the feed's copyright notice as a normal Python string.
        """

    feed_copyright = 'Copyright (c) 2007, Sally Smith' # Hard-coded copyright notice.

    # TTL -- One of the following three is optional. The framework looks
    # for them in this order. Ignored for Atom feeds.

    def ttl(self, obj):
        """
        Takes the object returned by get_object() and returns the feed's
        TTL (Time To Live) as a normal Python string.
        """

    def ttl(self):
        """
        Returns the feed's TTL as a normal Python string.
        """

    ttl = 600 # Hard-coded Time To Live.

    # ITEMS -- One of the following three is required. The framework looks
    # for them in this order.

    def items(self, obj):
        """
        Takes the object returned by get_object() and returns a list of
        items to publish in this feed.
        """

    def items(self):
        """
        Returns a list of items to publish in this feed.
        """

    items = ('Item 1', 'Item 2') # Hard-coded items.

    # GET_OBJECT -- This is required for feeds that publish different data
    # for different URL parameters. (See "A complex example" above.)

    def get_object(self, request, *args, **kwargs):
        """
        Takes the current request and the arguments from the URL, and
        returns an object represented by this feed. Raises
        django.core.exceptions.ObjectDoesNotExist on error.
        """

    # ITEM TITLE AND DESCRIPTION -- If title_template or
    # description_template are not defined, these are used instead. Both are
    # optional, by default they will use the unicode representation of the
    # item.

    def item_title(self, item):
        """
        Takes an item, as returned by items(), and returns the item's
        title as a normal Python string.
        """

    def item_title(self):
        """
        Returns the title for every item in the feed.
        """

    item_title = 'Breaking News: Nothing Happening' # Hard-coded title.

    def item_description(self, item):
        """
        Takes an item, as returned by items(), and returns the item's
        description as a normal Python string.
        """

    def item_description(self):
        """
        Returns the description for every item in the feed.
        """

    item_description = 'A description of the item.' # Hard-coded description.

    def get_context_data(self, **kwargs):
        """
        Returns a dictionary to use as extra context if either
        description_template or item_template are used.

        Default implementation preserves the old behavior
        of using {'obj': item, 'site': current_site} as the context.
        """

    # ITEM LINK -- One of these three is required. The framework looks for
    # them in this order.

    # First, the framework tries the two methods below, in
    # order. Failing that, it falls back to the get_absolute_url()
    # method on each item returned by items().

    def item_link(self, item):
        """
        Takes an item, as returned by items(), and returns the item's URL.
        """

    def item_link(self):
        """
        Returns the URL for every item in the feed.
        """

    # ITEM_GUID -- The following method is optional. If not provided, the
    # item's link is used by default.

    def item_guid(self, obj):
        """
        Takes an item, as return by items(), and returns the item's ID.
        """

    # ITEM_GUID_IS_PERMALINK -- The following method is optional. If
    # provided, it sets the 'isPermaLink' attribute of an item's
    # GUID element. This method is used only when 'item_guid' is
    # specified.

    def item_guid_is_permalink(self, obj):
        """
        Takes an item, as returned by items(), and returns a boolean.
        """

    item_guid_is_permalink = False  # Hard coded value

    # ITEM AUTHOR NAME -- One of the following three is optional. The
    # framework looks for them in this order.

    def item_author_name(self, item):
        """
        Takes an item, as returned by items(), and returns the item's
        author's name as a normal Python string.
        """

    def item_author_name(self):
        """
        Returns the author name for every item in the feed.
        """

    item_author_name = 'Sally Smith' # Hard-coded author name.

    # ITEM AUTHOR EMAIL --One of the following three is optional. The
    # framework looks for them in this order.
    #
    # If you specify this, you must specify item_author_name.

    def item_author_email(self, obj):
        """
        Takes an item, as returned by items(), and returns the item's
        author's email as a normal Python string.
        """

    def item_author_email(self):
        """
        Returns the author email for every item in the feed.
        """

    item_author_email = 'test@example.com' # Hard-coded author email.

    # ITEM AUTHOR LINK -- One of the following three is optional. The
    # framework looks for them in this order. In each case, the URL should
    # include the "http://" and domain name.
    #
    # If you specify this, you must specify item_author_name.

    def item_author_link(self, obj):
        """
        Takes an item, as returned by items(), and returns the item's
        author's URL as a normal Python string.
        """

    def item_author_link(self):
        """
        Returns the author URL for every item in the feed.
        """

    item_author_link = 'http://www.example.com/' # Hard-coded author URL.

    # ITEM ENCLOSURE URL -- One of these three is required if you're
    # publishing enclosures. The framework looks for them in this order.

    def item_enclosure_url(self, item):
        """
        Takes an item, as returned by items(), and returns the item's
        enclosure URL.
        """

    def item_enclosure_url(self):
        """
        Returns the enclosure URL for every item in the feed.
        """

    item_enclosure_url = "/foo/bar.mp3" # Hard-coded enclosure link.

    # ITEM ENCLOSURE LENGTH -- One of these three is required if you're
    # publishing enclosures. The framework looks for them in this order.
    # In each case, the returned value should be either an integer, or a
    # string representation of the integer, in bytes.

    def item_enclosure_length(self, item):
        """
        Takes an item, as returned by items(), and returns the item's
        enclosure length.
        """

    def item_enclosure_length(self):
        """
        Returns the enclosure length for every item in the feed.
        """

    item_enclosure_length = 32000 # Hard-coded enclosure length.

    # ITEM ENCLOSURE MIME TYPE -- One of these three is required if you're
    # publishing enclosures. The framework looks for them in this order.

    def item_enclosure_mime_type(self, item):
        """
        Takes an item, as returned by items(), and returns the item's
        enclosure MIME type.
        """

    def item_enclosure_mime_type(self):
        """
        Returns the enclosure MIME type for every item in the feed.
        """

    item_enclosure_mime_type = "audio/mpeg" # Hard-coded enclosure MIME type.

    # ITEM PUBDATE -- It's optional to use one of these three. This is a
    # hook that specifies how to get the pubdate for a given item.
    # In each case, the method/attribute should return a Python
    # datetime.datetime object.

    def item_pubdate(self, item):
        """
        Takes an item, as returned by items(), and returns the item's
        pubdate.
        """

    def item_pubdate(self):
        """
        Returns the pubdate for every item in the feed.
        """

    item_pubdate = datetime.datetime(2005, 5, 3) # Hard-coded pubdate.

    # ITEM UPDATED -- It's optional to use one of these three. This is a
    # hook that specifies how to get the updateddate for a given item.
    # In each case, the method/attribute should return a Python
    # datetime.datetime object.

    def item_updateddate(self, item):
        """
        Takes an item, as returned by items(), and returns the item's
        updateddate.
        """

    def item_updateddate(self):
        """
        Returns the updateddate for every item in the feed.
        """

    item_updateddate = datetime.datetime(2005, 5, 3) # Hard-coded updateddate.

    # ITEM CATEGORIES -- It's optional to use one of these three. This is
    # a hook that specifies how to get the list of categories for a given
    # item. In each case, the method/attribute should return an iterable
    # object that returns strings.

    def item_categories(self, item):
        """
        Takes an item, as returned by items(), and returns the item's
        categories.
        """

    def item_categories(self):
        """
        Returns the categories for every item in the feed.
        """

    item_categories = ("python", "django") # Hard-coded categories.

    # ITEM COPYRIGHT NOTICE (only applicable to Atom feeds) -- One of the
    # following three is optional. The framework looks for them in this
    # order.

    def item_copyright(self, obj):
        """
        Takes an item, as returned by items(), and returns the item's
        copyright notice as a normal Python string.
        """

    def item_copyright(self):
        """
        Returns the copyright notice for every item in the feed.
        """

    item_copyright = 'Copyright (c) 2007, Sally Smith' # Hard-coded copyright notice.

Низкоуровневая система

Под капотом, высокоуровневая система RSS использует низкоуровневую систему для генерации XML лент. Эта система находится в одном модуле: django/utils/feedgenerator.py.

Вы можете использовать эту систему самостоятельно для генерации лент на низком уровне. Вы также можете создать пользовательские подклассы генератора лент для использования с параметром feed_type Feed.

SyndicationFeed классы

Модуль feedgenerator содержит базовый класс:

  • django.utils.feedgenerator.SyndicationFeed

и несколько подклассов:

  • django.utils.feedgenerator.RssUserland091Feed
  • django.utils.feedgenerator.Rss201rev2Feed
  • django.utils.feedgenerator.Atom1Feed

Каждый из этих трёх классов знает, как отобразить определённый тип ленты как XML. Они разделяют этот интерфейс:

SyndicationFeed.__init__()

Инициализирует ленту заданным словарем метаданных, который относится ко всей ленте. Требуемые ключевые аргументы:

  • title
  • link
  • description

Также есть набор необязательных ключевых аргументов:

  • language
  • author_email
  • author_name
  • author_link
  • subtitle
  • categories
  • feed_url
  • feed_copyright
  • feed_guid
  • ttl

Любые дополнительные ключевые аргументы, которые вы передаёте в __init__, будут сохранены в self.feed для использования с пользовательскими генераторами лент.

Все параметры должны быть объектами Unicode, за исключением categories, который должен быть последовательностью объектов Unicode.

SyndicationFeed.add_item()

Добавляет элемент в ленту с заданными параметрами.

Требуемые ключевые аргументы:

  • title
  • link
  • description

Необязательные ключевые аргументы:

  • author_email
  • author_name
  • author_link
  • pubdate
  • comments
  • unique_id
  • enclosure
  • categories
  • item_copyright
  • ttl
  • updateddate

Дополнительные ключевые аргументы будут сохранены для пользовательских генераторов лент.

Все параметры, если указаны, должны быть объектами Unicode, за исключением:

  • pubdate должен быть объектом Python datetime.
  • updateddate должен быть объектом Python datetime.
  • enclosure должен быть экземпляром django.utils.feedgenerator.Enclosure.
  • categories должна быть последовательностью объектов Unicode.

Необязательный аргумент updateddate был добавлен.

SyndicationFeed.write()
Выводит ленту в заданной кодировке в outfile, который является объектом типа «файл».
SyndicationFeed.writeString()
Возвращает ленту в виде строки в заданной кодировке.

Например, чтобы создать ленту Atom 1.0 и вывести её в стандартный вывод:

>>> from django.utils import feedgenerator
>>> from datetime import datetime
>>> f = feedgenerator.Atom1Feed(
...     title="My Weblog",
...     link="http://www.example.com/",
...     description="In which I write about what I ate today.",
...     language="en",
...     author_name="Myself",
...     feed_url="http://example.com/atom.xml")
>>> f.add_item(title="Hot dog today",
...     link="http://www.example.com/entries/1/",
...     pubdate=datetime.now(),
...     description="<p>Today I had a Vienna Beef hot dog. It was pink, plump and perfect.</p>")
>>> print(f.writeString('UTF-8'))
<?xml version="1.0" encoding="UTF-8"?>
<feed xmlns="http://www.w3.org/2005/Atom" xml:lang="en">
...
</feed>

Пользовательские генераторы лент

Если вам нужно создать ленту в пользовательском формате, у вас есть несколько вариантов.

Если формат ленты полностью пользовательский, вам следует подклассировать SyndicationFeed и полностью заменить методы write() и writeString().

Однако, если формат ленты является производным от RSS или Atom (например, GeoRSS, формат подкастов Apple iTunes и т. д.), у вас есть лучший вариант. Такие типы лент обычно добавляют дополнительные элементы и/или атрибуты к базовому формату, и есть набор методов, которые SyndicationFeed вызывает для получения этих дополнительных атрибутов. Таким образом, вы можете подклассировать соответствующий класс генератора лент (Atom1Feed или Rss201rev2Feed) и расширить эти обратные вызовы. Это:

SyndicationFeed.root_attributes(self, )
Возвращает dict атрибутов, которые нужно добавить к корневому элементу канала (feed/channel).
SyndicationFeed.add_root_elements(self, handler)
Обработчик для добавления элементов внутри корневого элемента канала (feed/channel). handler — это XMLGenerator из встроенной библиотеки SAX Python; вы будете вызывать методы для добавления элементов в XML-документ по ходу процесса.
SyndicationFeed.item_attributes(self, item)
Возвращает dict атрибутов, которые нужно добавить к каждому элементу (item/entry) канала. Аргумент item — это словарь всей информации, переданной в SyndicationFeed.add_item().
SyndicationFeed.add_item_elements(self, handler, item)
Обработчик для добавления элементов к каждому элементу канала (item/entry). handler и item — те же, что и выше.

Предупреждение

Если вы переопределяете любой из этих методов, убедитесь, что вызываете методы суперкласса, так как они добавляют необходимые элементы для каждого формата канала.

Например, вы можете начать реализацию генератора канала iTunes RSS следующим образом:

class iTunesFeed(Rss201rev2Feed):
    def root_attributes(self):
        attrs = super(iTunesFeed, self).root_attributes()
        attrs['xmlns:itunes'] = 'http://www.itunes.com/dtds/podcast-1.0.dtd'
        return attrs

    def add_root_elements(self, handler):
        super(iTunesFeed, self).add_root_elements(handler)
        handler.addQuickElement('itunes:explicit', 'clean')

Очевидно, для полной реализации пользовательского класса канала требуется ещё много работы, но приведенный выше пример демонстрирует основную идею.

© Django Software Foundation and individual contributors
Licensed under the BSD License.
https://docs.djangoproject.com/en/1.8/ref/contrib/syndication/

Spec-Zone.ru

Настройки Оффлайн Что нового Помощь О нас
Spec-Zone .ru
спецификации, руководства, описания, API