目次
シンジケーションフィードフレームワーク
Djangoには、 RSS および Atom フィードを作成するための高レベルのシンジケーションフィード生成フレームワークが付属しています。
シンジケーションフィードを作成するには、短いPythonクラスを作成するだけです。 必要な数のフィードを作成できます。
Djangoには、低レベルのフィード生成APIも付属しています。 これは、Webコンテキストの外部、またはその他の低レベルの方法でフィードを生成する場合に使用します。
高レベルのフレームワーク
Feedクラス
Feed クラスは、シンジケーションフィードを表すPythonクラスです。 フィードは、単純なもの(たとえば、「サイトニュース」フィード、またはブログの最新のエントリを表示する基本的なフィード)またはより複雑なもの(たとえば、カテゴリが可変である特定のカテゴリのすべてのブログエントリを表示するフィード)にすることができます。 )。
フィードクラスサブクラス django.contrib.syndication.views.Feed 。 彼らはあなたのコードベースのどこにでも住むことができます。
Feed クラスのインスタンスは、 URLconf で使用できるビューです。
簡単な例
この簡単な例は、架空の警察のビートニュースサイトから抜粋したもので、最新の5つのニュースアイテムのフィードについて説明しています。
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>
要素としてフィードに含める必要のあるオブジェクトのリストを返すメソッドです。 この例では、Djangoのオブジェクトリレーショナルマッパーを使用してNewsItem
オブジェクトを返しますが、items()
はモデルインスタンスを返す必要はありません。 Djangoモデルを使用すると、「無料」で数ビットの機能を利用できますが、items()
は任意のタイプのオブジェクトを返すことができます。- RSSフィードではなくAtomフィードを作成する場合は、
description
属性の代わりにsubtitle
属性を設定してください。 例については、後で AtomフィードとRSSフィードをタンデムで公開するを参照してください。
やるべきことが1つ残っています。 RSSフィードでは、各<item>
に<title>
、<link>
、および<description>
があります。 これらの要素にどのデータを入れるかをフレームワークに伝える必要があります。
<title>
と<description>
のコンテンツについて、Djangoは Feed クラスのメソッドitem_title()
とitem_description()
を呼び出そうとします。 これらには、オブジェクト自体である単一のパラメーターitem
が渡されます。 これらはオプションです。 デフォルトでは、オブジェクトの文字列表現が両方に使用されます。タイトルまたは説明のいずれかに特別なフォーマットを行う場合は、代わりに Djangoテンプレートを使用できます。 それらのパスは、 Feed クラスの
title_template
およびdescription_template
属性で指定できます。 テンプレートはアイテムごとにレンダリングされ、2つのテンプレートコンテキスト変数が渡されます。テンプレート:Obj
–現在のオブジェクト(items()
で返されたオブジェクトの1つ)。テンプレート:Site
–現在のサイトを表す django.contrib.sites.models.Site オブジェクト。 これは、テンプレート:Site.domain
またはテンプレート:Site.name
に役立ちます。 にDjangoサイトフレームワークがインストールされていない場合、これは RequestSite オブジェクトに設定されます。 詳細については、サイトフレームワークドキュメントの RequestSiteセクションを参照してください。
説明テンプレートを使用する以下の複雑な例を参照してください。
- Feed.get_context_data(**kwargs)
前述の2つ以上の変数を指定する必要がある場合は、タイトルと説明のテンプレートに追加情報を渡す方法もあります。
Feed
サブクラスでget_context_data
メソッドの実装を提供できます。 例えば: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()
によって返されるリスト内の各項目ごとに、次のキーワード引数を使用して1回呼び出されます。item
:現在のアイテム。 下位互換性の理由から、このコンテキスト変数の名前はテンプレート:Obj
です。obj
:get_object()
によって返されるオブジェクト。 デフォルトでは、これはテンプレート:Obj
(上記を参照)との混同を避けるためにテンプレートに公開されていませんが、get_context_data()
の実装で使用できます。site
:上記の現在のサイト。request
:現在のリクエスト。
get_context_data()
の動作は、ジェネリックビューの動作を模倣しています。super()
を呼び出して、親クラスからコンテキストデータを取得し、データを追加して、変更された辞書を返すことになっています。<link>
の内容を指定するには、2つのオプションがあります。items()
の各アイテムについて、Djangoは最初に Feed クラスでitem_link()
メソッドを呼び出そうとします。 タイトルと説明と同様に、単一のパラメーターitem
が渡されます。 そのメソッドが存在しない場合、Djangoはそのオブジェクトに対してget_absolute_url()
メソッドを実行しようとします。get_absolute_url()
とitem_link()
はどちらも、アイテムのURLを通常のPython文字列として返す必要があります。get_absolute_url()
と同様に、item_link()
の結果はURLに直接含まれるため、メソッド自体の内部で必要なすべてのURL引用とASCIIへの変換を行う必要があります。
複雑な例
フレームワークは、引数を介して、より複雑なフィードもサポートします。
たとえば、Webサイトでは、都市で警察が殴打するたびに、最近の犯罪のRSSフィードを提供できます。 警察のビートごとに個別の Feed クラスを作成するのはばかげています。 これは DRYの原則に違反し、データをプログラミングロジックに結合します。 代わりに、シンジケーションフレームワークを使用すると、 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は次のアルゴリズムに従います。
- まず、
obj
引数を渡してメソッドを呼び出そうとします。ここで、obj
はget_object()
によって返されるオブジェクトです。 - それが失敗すると、引数なしでメソッドを呼び出そうとします。
- それができない場合は、class属性を使用します。
また、items()
も同じアルゴリズムに従うことに注意してください。最初に、items(obj)
、次にitems()
、最後にitems
クラス属性(リスト)。
アイテムの説明にはテンプレートを使用しています。 これと同じくらい最小限にすることができます:
{{ obj.description }}
ただし、必要に応じてフォーマットを自由に追加できます。
以下のExampleFeed
クラスは、 Feed クラスのメソッドと属性に関する完全なドキュメントを提供します。
飼料の種類を指定する
デフォルトでは、このフレームワークで作成されたフィードはRSS2.0を使用します。
これを変更するには、次のようにfeed_type
属性を Feed クラスに追加します。
from django.utils.feedgenerator import Atom1Feed
class MyFeed(Feed):
feed_type = Atom1Feed
feed_type
をインスタンスではなくクラスオブジェクトに設定することに注意してください。
現在利用可能なフィードタイプは次のとおりです。
- django.utils.feedgenerator.Rss201rev2Feed (RSS2.01。 ディフォルト。)
- django.utils.feedgenerator.RssUserland091Feed (RSS 0.91。)
- django.utils.feedgenerator.Atom1Feed (Atom 1.0)
エンクロージャー
ポッドキャストフィードの作成に使用されるエンクロージャーなどを指定するには、item_enclosures
フックを使用するか、アイテムごとにエンクロージャーが1つしかない場合は、item_enclosure_url
、item_enclosure_length
、およびitem_enclosure_mime_type
フック。 使用例については、以下のExampleFeed
クラスを参照してください。
言語
シンジケーションフレームワークによって作成されたフィードには、適切な<language>
タグ(RSS 2.0)またはxml:lang
属性(Atom)が自動的に含まれます。 デフォルトでは、これは django.utils.translation.get_language()です。 language
クラス属性を設定することで変更できます。
URL
link
メソッド/属性は、絶対パス(例: "/blog/"
)または完全修飾ドメインとプロトコルを含むURL(例: "https://www.example.com/blog/%22
)。 もしもlink
ドメインを返さない場合、シンジケーションフレームワークは、現在のサイトのドメインを挿入します。 :setting: `SITE_ID設定 ` 。
Atomフィードには、フィードの現在の場所を定義する<link rel="self">
が必要です。 シンジケーションフレームワークは、:setting: `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
属性を定義する必要があります。
上記の例では、Atomフィードのsubtitle
をRSSフィードのdescription
に設定しています。これは、すでにかなり短いためです。
そして付随する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 = '[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.
# 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
バージョン3.2で変更:フィードアイテムごとのコメントURLのサポートが、item_comments
フックを介して追加されました。
低レベルのフレームワーク
舞台裏では、高レベルのRSSフレームワークは、フィードのXMLを生成するために低レベルのフレームワークを使用します。 このフレームワークは、:source: `django / utils / feedgenerator.py` という単一のモジュールに存在します。
このフレームワークは、低レベルのフィード生成のために独自に使用します。 feed_type
Feed
オプションで使用するカスタムフィードジェネレータサブクラスを作成することもできます。
SyndicationFeedクラス
feedgenerator モジュールには、基本クラスが含まれています。
およびいくつかのサブクラス:
django.utils.feedgenerator.RssUserland091Feed
django.utils.feedgenerator.Rss201rev2Feed
django.utils.feedgenerator.Atom1Feed
これらの3つのクラスはそれぞれ、特定のタイプのフィードを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
は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 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
は、Pythonの組み込みSAXライブラリのXMLGenerator
です。 そのメソッドを呼び出して、処理中のXMLドキュメントに追加します。 SyndicationFeed.item_attributes(self, item)
- 各アイテム(
item
/entry
)要素に追加する属性のdict
を返します。 引数item
は、SyndicationFeed.add_item()
に渡されるすべてのデータの辞書です。 SyndicationFeed.add_item_elements(self, handler, item)
- 各アイテム(
item
/entry
)要素に要素を追加するためのコールバック。handler
とitem
は上記のとおりです。
警告
これらのメソッドのいずれかをオーバーライドする場合は、フィード形式ごとに必要な要素が追加されるため、必ずスーパークラスメソッドを呼び出してください。
たとえば、次のようにiTunesRSSフィードジェネレータの実装を開始できます。
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')
完全なカスタムフィードクラスを作成するには、さらに多くの作業を行う必要がありますが、上記の例は基本的な考え方を示しているはずです。