Инфраструктура синдикации потока

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

Чтобы создать канал распространения, все, что вам нужно сделать, это написать короткий класс Python. Вы можете создать столько потока, сколько вам нужно.

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

Инфраструктура высокого уровня

Предварительный просмотр

Инфраструктура для создания высокоуровневых каналов синдикации предоставляется классом Feed . Чтобы создать поток, напишите класс Feed и укажите его конфигурацию URL-адреса .

Классы Feed (потоки)

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

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

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

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

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

from django.contrib.syndication.views import Feed
from django.urls 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.urls import path
from myproject.feeds import LatestEntriesFeed

urlpatterns = [
    # ...
    path('latest/feed/', LatestEntriesFeed()),
    # ...
]

Примечание :

  • Класс потока наследуется от django.contrib.syndication.views.Feed .
  • title ,, link и description соответствуют элементам <title> , <link> и <description> стандарта RSS.
  • items() - это метод, который возвращает список объектов, которые должны быть включены в поток потока как элементы <item> . Хотя этот пример возвращает объекты NewsItem с помощью Django QuerySet API , 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 представляющий текущий сайт. Это полезно для или . Если вы не установили фреймворк сайтов Django, это будет объект . См. Дополнительную информацию в документации по структуре сайта .{{ site.domain }} {{ site.name }} 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().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 . Аналогично атрибутам title и description метод получает единственный параметр item . Если этот метод не существует, Django пытается вызвать метод get_absolute_url() этого объекта. А также в get_absolute_url() качестве item_link() URL - элемента должен возвращать в качестве обычной строки Python. Как и в случае get_absolute_url() , результат item_link() будет напрямую включен в URL-адрес, поэтому вы несете ответственность за выполнение всех необходимых операций (экранирование, преобразование в ASCII) в самом методе.

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

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

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

Доступ к каналу Police Sector можно получить через URL-адреса, например:

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

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

path('beats/<int:beat_id>/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() .
  • Если это не удается, он пытается вызвать метод без параметров.
  • В крайнем случае он использует атрибут class.

Также обратите внимание, что 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 это определено для объекта класса, а не для экземпляра.

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

Приложения

Чтобы определить приложения, такие как те , которые используются для создания подкастов каналов, используйте точку входа item_enclosures или, в случае , если у вас есть только одно приложения за единицу, точки входа item_enclosure_url , item_enclosure_length и item_enclosure_mime_type . ExampleFeed Примеры использования см. В приведенном ниже классе .

Язык

Каналы, созданные инфраструктурой синдикации, автоматически включают <language> правильный тег (RSS 2.0) или атрибут xml:lang (Atom). По умолчанию это соответствует django.utils.translation.get_language() . Вы можете изменить его, установив атрибут класса language .

Изменено в Django 3.0:

Атрибут класса language был добавлен. В предыдущих версиях поведение было эквивалентно .language = settings.LANGUAGE_CODE

URL

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

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

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

Некоторым разработчикам нравится делать доступными как Atom, так и RSS- версии своих каналов. Для этого вы можете создать подкласс своего класса Feed и установить feed_type другое значение. Затем обновите конфигурацию URL-адреса, чтобы добавить дополнительные версии.

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

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, поскольку канал RSS уже был довольно коротким.

А также связанная с ним конфигурация URL:

from django.urls import path
from myproject.feeds import AtomSiteNewsFeed, RssSiteNewsFeed

urlpatterns = [
    # ...
    path('sitenews/rss/', RssSiteNewsFeed()),
    path('sitenews/atom/', AtomSiteNewsFeed()),
    # ...
]

Ссылка на класс потока Feed

класс 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

    # LANGUAGE -- Optional. This should be a string specifying a language
    # code. Defaults to django.utils.translation.get_language().
    language = 'de'

    # 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 = '[email protected]' # 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 = 'https://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 string 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 = '[email protected]' # 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 = 'https://www.example.com/' # Hard-coded author URL.

    # ITEM ENCLOSURES -- One of the following three is optional. The
    # framework looks for them in this order. If one of them is defined,
    # ``item_enclosure_url``, ``item_enclosure_length``, and
    # ``item_enclosure_mime_type`` will have no effect.

    def item_enclosures(self, item):
        """
        Takes an item, as returned by items(), and returns a list of
        ``django.utils.feedgenerator.Enclosure`` objects.
        """

    def item_enclosures(self):
        """
        Returns the ``django.utils.feedgenerator.Enclosure`` list for every
        item in the feed.
        """

    item_enclosures = []  # Hard-coded enclosure list

    # ITEM ENCLOSURE URL -- One of these three is required if you're
    # publishing enclosures and you're not using ``item_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 and you're not using ``item_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 and you're not using ``item_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 содержит базовый класс:

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

Каждый из этих трех классов знает, как создать какой-либо канал в форме 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 для использования настраиваемыми генераторами потока .

Все параметры должны быть строками, за исключением categories последовательности строк. Остерегайтесь некоторых управляющих символов, которые недопустимы в XML-документах. Если содержание содержит некоторые, вы можете столкнуться исключением ValueError при производстве потока.

SyndicationFeed.add_item()

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

Обязательные именованные параметры:

  • title
  • link
  • description

Необязательные именованные параметры:

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

Дополнительные именованные параметры сохраняются для настраиваемых построителей потока .

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

  • pubdate должен быть объектом Python datetime .
  • updateddate должен быть объектом Python datetime .
  • enclosures должен быть список экземпляров django.utils.feedgenerator.Enclosure .
  • categories должен быть списком строк.
SyndicationFeed.write()
Создает поток в указанной кодировке outfile , который является объектом типа файла.
SyndicationFeed.writeString()
Возвращает поток в виде строки в указанной кодировке.

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

>>> from django.utils import feedgenerator
>>> from datetime import datetime
>>> f = feedgenerator.Atom1Feed(
...     title="My Weblog",
...     link="https://www.example.com/",
...     description="In which I write about what I ate today.",
...     language="en",
...     author_name="Myself",
...     feed_url="https://example.com/atom.xml")
>>> f.add_item(title="Hot dog today",
...     link="https://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 идентичны тому, что описано выше.

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

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

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

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

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

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

Copyright ©2021 All rights reserved