Фреймворк лент syndication
Django включает высокоуровневый фреймворк для создания лент syndication, позволяющий создавать ленты RSS и Atom.
Чтобы создать любую ленту syndication, достаточно написать короткий класс Python. Вы можете создать любое количество лент.
Django также включает низкоуровневый API для создания лент. Используйте его, если хотите создавать ленты вне веб-контекста или другим низкоуровневым способом.
Высокоуровневый фреймворк
Обзор
Высокоуровневый фреймворк для создания лент предоставляется классом Feed. Чтобы создать ленту, напишите класс Feed и укажите экземпляр этого класса в своём URLconf.
Классы Feed
Класс Feed — это класс Python, представляющий ленту syndication. Лента может быть простой (например, лента «Новости сайта» или базовая лента с последними записями блога) либо более сложной (например, лента со всеми записями блога в определённой категории, где категория задаётся динамически).
Классы лент наследуются от django.contrib.syndication.views.Feed. Они могут находиться в любом месте вашей кодовой базы.
Экземпляры классов Feed — это представления, которые можно использовать в своём URLconf.
Простой пример
В этом простом примере, взятом с гипотетического новостного сайта полиции, описана лента с пятью последними новостями:
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 в свой URLconf. Например:
from django.urls import path
from myproject.feeds import LatestEntriesFeed
urlpatterns = [
# ...
path("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().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 и связало бы данные с программной логикой. Вместо этого фреймворк syndication позволяет получать аргументы, переданные из вашего URLconf, чтобы ленты могли выводить элементы на основе информации в URL ленты.
Ленты участков полиции могут быть доступны по URL, например:
-
/beats/613/rss/— возвращает недавние преступления для участка 613. -
/beats/1424/rss/— возвращает недавние преступления для участка 1424.
Их можно сопоставить со строкой URLconf, например:
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 выполняет следующий алгоритм:
- Сначала Django пытается вызвать метод, передав аргумент
obj, гдеobj— объект, возвращённый методомget_object(). - Если это не удаётся, Django пытается вызвать метод без аргументов.
- Если и это не удаётся, Django использует атрибут класса.
Обратите также внимание, что 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_enclosures или, если для каждого элемента предусмотрено только одно вложение, хуки item_enclosure_url, item_enclosure_length и item_enclosure_mime_type. Примеры использования см. в классе ExampleFeed ниже.
Язык
Ленты, созданные фреймворком syndication, автоматически включают соответствующий тег <language> (RSS 2.0) или атрибут xml:lang (Atom). По умолчанию используется django.utils.translation.get_language(). Это можно изменить, задав атрибут класса language.
URL
Метод/атрибут link может возвращать абсолютный путь (например, "/blog/") или URL с полным доменным именем и протоколом (например, "https://www.example.com/blog/"). Если link не возвращает домен, фреймворк syndication добавит домен текущего сайта в соответствии с настройкой SITE_ID setting.
Для лент Atom требуется <link rel="self">, определяющий текущее местоположение ленты. Фреймворк syndication заполняет его автоматически, используя домен текущего сайта согласно настройке SITE_ID.
Одновременная публикация лент Atom и RSS
Некоторые разработчики предпочитают предоставлять ленты и в формате Atom, и в формате RSS. Для этого можно создать подкласс класса 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 не предусматривают «описание» на уровне ленты, но предусматривают «подзаголовок».
Если в классе Feed задан атрибут description, Django не будет автоматически помещать его в элемент subtitle, поскольку подзаголовок и описание не обязательно означают одно и то же. Вместо этого следует определить атрибут subtitle.
В примере выше мы задали для subtitle ленты Atom значение description RSS-ленты, поскольку оно и так достаточно короткое.
И соответствующий URLconf:
from django.urls import path
from myproject.feeds import AtomSiteNewsFeed, RssSiteNewsFeed
urlpatterns = [
# ...
path("sitenews/rss/", RssSiteNewsFeed()),
path("sitenews/atom/", AtomSiteNewsFeed()),
# ...
]
Справочник по классу Feed
-
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
# 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 = "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 scheme (such as "https://") 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.
# STYLESHEETS -- Optional. To set, provide one of the following three.
# The framework looks for them in this order.
def stylesheets(self, obj):
"""
Takes the object returned by get_object() and returns the feed's
stylesheets (as URL strings or as Stylesheet instances).
"""
def stylesheets(self):
"""
Returns the feed's stylesheets (as URL strings or Stylesheet
instances).
"""
# Hardcoded stylesheets.
stylesheets = ["/stylesheet1.xsl", "stylesheet2.xsl"]
# 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 # Hardcoded 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 scheme (such as "https://") 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.
# ITEM COMMENTS URL -- It's optional to use one of these three. This is
# a hook that specifies how to get the URL of a page for comments for a
# given item.
def item_comments(self, obj):
"""
Takes an item, as returned by items(), and returns the item's
comments URL as a normal Python string.
"""
def item_comments(self):
"""
Returns the comments URL for every item in the feed.
"""
item_comments = "https://www.example.com/comments" # Hard-coded comments URL
Низкоуровневый фреймворк
За кулисами высокоуровневый фреймворк RSS использует низкоуровневый фреймворк для создания XML лент. Этот фреймворк находится в одном модуле: django/utils/feedgenerator.py.
Этот фреймворк можно использовать самостоятельно для низкоуровневого создания лент. Вы также можете создавать собственные подклассы генераторов лент для использования с параметром feed_type Feed.
Классы SyndicationFeed
Модуль feedgenerator содержит базовый класс:
и несколько подклассов:
django.utils.feedgenerator.RssUserland091Feeddjango.utils.feedgenerator.Rss201rev2Feeddjango.utils.feedgenerator.Atom1Feed
Каждый из этих трёх классов умеет представлять определённый тип ленты в формате XML. У них общий интерфейс:
-
SyndicationFeed.__init__() -
Инициализирует ленту указанным словарём метаданных, применяемых ко всей ленте. Обязательные именованные аргументы:
titlelinkdescription
Также есть несколько других необязательных именованных аргументов:
languageauthor_emailauthor_nameauthor_linksubtitlecategoriesfeed_urlfeed_copyrightfeed_guidttlstylesheets
Все дополнительные именованные аргументы, переданные в
__init__, будут сохранены вself.feedдля использования в собственных генераторах лент.Все параметры должны быть строками, кроме двух:
-
categoriesдолжен быть последовательностью строк. -
stylesheetsдолжен быть последовательностью строк или экземпляровStylesheet.
Помните, что некоторые управляющие символы не допускаются в документах XML. Если в содержимом есть такие символы, при создании ленты может возникнуть исключение
ValueError.Изменено в Django 5.2:Добавлен аргумент
stylesheets. -
SyndicationFeed.add_item() -
Добавляет элемент в ленту с заданными параметрами.
Обязательные именованные аргументы:
titlelinkdescription
Необязательные именованные аргументы:
author_emailauthor_nameauthor_linkpubdatecommentsunique_idenclosurescategoriesitem_copyrightttlupdateddate
Дополнительные именованные аргументы будут сохранены для собственных генераторов лент.
Все заданные параметры должны быть строками, кроме следующих:
-
pubdateдолжен быть объектом Pythondatetime. -
updateddateдолжен быть объектом Pythondatetime. -
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 Blog",
... 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, формат подкастов iTunes от Apple и т. д.), есть более подходящий вариант. Такие ленты обычно добавляют дополнительные элементы и/или атрибуты в базовый формат; для получения этих дополнительных атрибутов предусмотрен набор методов, вызываемых методом 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")
Для полноценного собственного класса ленты предстоит сделать ещё многое, но приведённый выше пример демонстрирует основную идею.
Таблицы стилей лент
Чтобы RSS-лента корректно отображалась в браузере, необходимо предоставить сведения о стилях XML-файла, обычно в формате XSLT или CSS.
Добавить их в RSS-ленту можно, задав атрибут stylesheets в классе ленты.
Можно указать жёстко заданный URL:
from django.contrib.syndication.views import Feed
class FeedWithHardcodedStylesheet(Feed):
stylesheets = [
"https://example.com/rss_stylesheet.xslt",
]
Также можно воспользоваться системой статических файлов Django:
from django.contrib.syndication.views import Feed
from django.templatetags.static import static
class FeedWithStaticFileStylesheet(Feed):
stylesheets = [
static("rss_styles.xslt"),
]
Ещё один вариант — создать в проекте представление, отображающее документ XSLT. Затем на него можно сослаться так:
from django.contrib.syndication.views import Feed
from django.urls import reverse_lazy
class FeedWithStylesheetView(Feed):
stylesheets = [
reverse_lazy("your-custom-view-name"),
]
Обычно Django пытается определить MIME-тип заданного URL по его расширению, но если это не удаётся, тип можно указать с помощью класса Stylesheet:
from django.contrib.syndication.views import Feed
from django.utils.feedgenerator import Stylesheet
class FeedWithHardcodedStylesheet(Feed):
stylesheets = [
Stylesheet("https://example.com/rss_stylesheet", mimetype="text/xsl"),
]
Аналогично, если вместо screen (значение по умолчанию в Django) нужно использовать другой атрибут media, можно снова воспользоваться классом Stylesheet:
from django.contrib.syndication.views import Feed
from django.utils.feedgenerator import Stylesheet
class FeedWithHardcodedStylesheet(Feed):
stylesheets = [
Stylesheet("https://example.com/rss_stylesheet.xslt", media="print"),
]
При использовании нескольких таблиц стилей можно комбинировать любые из этих вариантов:
from django.contrib.syndication.views import Feed
from django.utils.feedgenerator import Stylesheet
class MultiStylesheetFeed(Feed):
stylesheets = [
"/stylesheet1.xsl",
Stylesheet("/stylesheet2.xsl"),
]
© Django Software Foundation and individual contributors
Licensed under the BSD License.
https://docs.djangoproject.com/en/6.0/ref/contrib/syndication/