An creat beatha sindiciúcháinLink to this heading

<4287>Tagann Django le creat ardleibhéil giniúna sindiúcháin beatha chun fothaí RSS agus:rfc: Atom a chruthú.

Chun aon bheatha sindicíochta a chruthú, níl le déanamh agat ach rang gairid Python a scríobh. Is féidir leat an oiread fothaí a chruthú agus is mian leat.

Tagann Django le API a ghiniúint beatha leibhéal níos ísle freisin. Úsáid é seo más mian leat fothaí a ghiniúint lasmuigh de chomhthéacs gréasáin, nó ar bhealach eile ar leibhéal níos ísle.

An creat ardleibhéilLink to this heading

ForbhreathnúLink to this heading

Soláthraíonn an creat giniúna beatha ardleibhéil ag an rang:class: ~django.contrib.Syndication.Views.Feed. Chun fotha a chruthú, scríobh a:class: ~django.contrib.syndication.views.</topics/http/urls> feed aicme agus cuir in iúl ar shampla de i d:doc: URLConf.

Ranganna FeedLink to this heading

A: Class: ~django.contrib.syndication.views.feed aicme Python é rang a léiríonn beatha sindiciúcháin. Is féidir le beatha a bheith simplí (m.sh., fotha “nuacht láithreáin”, nó fotha bunúsach a thaispeánann na hiontrálacha is déanaí de bhlag) nó níos casta (m.sh., fotha a thaispeánann na hiontrálacha blag go léir i gcatagóir áirithe, áit a bhfuil an catagóir athraitheach).

Ranganna beatha fo-rang:class: django.contrib.syndication.views.feed. Is féidir leo maireachtáil áit ar bith i do bhunachar cóid.

Is tuairimí iad cásanna de:class: ~django.contrib.syndication.views.feed ranganna is féidir a úsáid i d:doc: URLCon</topics/http/urls> f.

Sampla simplíLink to this heading

Déanann an sampla simplí seo, tógtha ó shuíomh nuachta buailte póilíní hipitéiseach cur síos ar bheatha de na cúig mhír nuachta is déanaí:

Code
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])

Chun URL a nascadh leis an bhfotha seo, cuir sampla den réad Featha i d:doc: </topics/http/urls> URLConf. Mar shampla:

Code
from django.urls import path
from myproject.feeds import LatestEntriesFeed

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

Nóta:

  • Fo-aicmí an rang Feath:class: django.contrib.syndication.views.feed.

  • <title><link><description>Freagraíonn teideal ``, `nasc agus `tuairisc do na heilimintí caighdeánacha RSS`` ,, agus `` ``, `` `` ``, `` `` , `` , ``, `` ``,

  • <item>Is é items () `, modh a thugann liosta rudaí ar ais ar chóir a chur san áireamh sa bheatha mar eilimintí `. Cé go bhfilleann an sampla seo rudaí newsitem ag baint úsáide as django's:doc: object-relational mapper, ní gá items () ``</ref/models/querysets> cásanna samhail a thabhairt ar ais. go bhfaigheann cúpla giotán feidhmiúlachta “saor in aisce” trí mhúnlaí Django a úsáid, is féidir le ``items () aon chineál réada a theastaíonn uait a thabhairt ar ais.

  • Má tá fotha Atom á chruthú agat, seachas fotha RSS, socraigh an tréith fotheideal ``in ionad an tréith ``Description. Féach Foilsiú fothaí Atom agus RSS i tandem, níos déanaí, mar shampla.

Tá rud amháin fágtha le déanamh. <link><description>I bhfotha RSS, tá ``, ``<item>, agus ```` <title>` ag gach ``` ``. Ní mór dúinn a insint don chreat cad iad na sonraí atá le cur sna heilimintí sin.

  • Maidir le hábhar ```` agus <title>````<description>,,,, Déanann Django iarracht na modhanna item_title () agus item_description () a ghlaoch ar an aicme:class: ~django.contrib.syndication.views.feed. Cuirtear paraiméadar amháin orthu, earra, arb é an réad féin. Tá siad seo roghnach; de réir réamhshocraithe, úsáidtear léiriú teaghrán an réada don dá rud.

    Más mian leat aon fhormáidiú speisialta a dhéanamh don teideal nó don tuairisc, is féidir :doc: teimpléid Django 'a úsáid ina ionad </ref/templates/language>. Is féidir a gcosáin a shonrú leis na tréithe ``title_template` agus description_template` ar an aicme:class: ~django.contrib.syndication.views.feed. Déantar na teimpléid a rinneadh do gach mír agus cuirtear dhá athróg comhthéacs teimpléad ar

    • {{obj}} -- An réad reatha (ceann de na rudaí a chuir tú ar ais i ``items () ``).

    • {{site}} -- a:Class: django.contrib.sites.models.site réad a léiríonn an láithreán reatha. Tá sé seo úsáideach do {{site.domain}}{{site.name}}. Mura bhfuil creat láithreáin Django suiteáilte agat*, socraítear é seo ar a:class: ~django.contrib.sites.requests.requestsite réad. <requestsite-objects>Féach an:ref: `RequestSite de dhoiciméadú creat na láithreáin `le haghaidh tuilleadh eolais.

    Féach sampla casta thíos a úsáideann teimpléad tuairisc.

    Feed.get_context_data(**kwargs)Link to this definition

    Tá bealach ann freisin chun faisnéis bhreise a chur chuig teimpléid teidil agus tuairisc, más gá duit níos mó ná an dá athróg a luaitear roimhe seo a sholáthar. Is féidir leat cur i bhfeidhm modh get_context_data ``a sholáthar i do fho-aicme ``Feed. Mar shampla:

    Code
    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
    

    Agus an teimpléad:

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

    Glaofar an modh seo uair amháin in aghaidh gach míre sa liosta a chuirtear ar ais ag `items () ``leis na hargóintí eochairfhocal seo a leanas:

    • earra: an mír reatha. Ar chúiseanna comhoiriúnachta ar chúl, is é {{obj}} ainm an athróg comhthéacs seo.

    • obj: an réad ar ais ag get_object () ``. De réir réamhshocraithe níl seo nochtaithe do na teimpléid chun mearbhall a sheachaint le ``{{obj}} (féach thuas), ach is féidir leat é a úsáid chun ``get_context_data () `a chur i bhfeidhm.

    • suite: suíomh reatha mar a thuairiscítear thuas.

    • iarraidh: iarratas reatha.

    Déanann iompar get_context_data () ``aithris ar iompar: ref: `tuairimí cineálacha `<adding-extra-context>- ceaptar duit glaoch ar ``super () chun sonraí comhthéacs a aisghabháil ó rang tuismitheoirí, do chuid sonraí a chur leis agus an foclóir modhnaithe a thabhairt ar ais.

  • Chun ábhar <link>```a shonrú, tá dhá rogha agat. Maidir le gach mír i items () `, déanann Django iarracht an modh item_link () a ghlaoch ar dtús ar an aicme:class: ~django.contrib.syndication.views.feed. Ar bhealach cosúil leis an teideal agus an tuairisc, cuirtear paraiméadar amháin air, earra. Mura bhfuil an modh sin ann, déanann Django iarracht modh get_absolute_url () `a fhorghníomhú ar an réad sin. Ba chóir go gcuirfeadh ``get_absolute_url () ``agus ``item_link () URL an earra ar ais mar ghnáthshreang Python. Mar is amhlaidh le get_absolute_url () ``, cuirfear toradh ``item_link () san áireamh go díreach sa URL, mar sin tá tú freagrach as gach luachan URL riachtanach agus tiontú go ASCII a dhéanamh taobh istigh den mhodh féin.

Sampla castaLink to this heading

Tacaíonn an creat le fothaí níos casta freisin, trí argóintí.

Mar shampla, d'fhéadfadh suíomh Gréasáin fotha RSS de choireanna le déanaí a thairiscint do gach bualadh póilíní i gcathair. <dry>Bheadh sé amaideach rang ar leithligh: class: ~django.contrib.syndication.views.feed a chruthú do gach bualadh póilíní; a sháródh sé prionsabal: ref: DRY `agus chuirfeadh sonraí a cheangal le loighic cláraithe. Ina áit sin, ligeann an creat sindiciúcháin duit rochtain a fháil ar na hargóintí a rith ó do: doc: `URLConf </topics/http/urls> ionas gur féidir le fothaí míreanna a aschur bunaithe ar fhaisnéis i URL an bheatha.

D'fhéadfadh fothaí buailte póilíní a bheith inrochtana trí URLanna mar seo:

  • /beats/613/rss/ -- Tugann sé coireanna le déanaí ar bhuail 613.

  • /beats/1424/rss/ -- Tugann sé coireanna le déanaí ar bhuail 1424.

Is féidir iad seo a mheaitseáil le a: doc: URLConf líne mar </topics/http/urls>:

Code
path("beats/<int:beat_id>/rss/", BeatFeed()),

Cosúil le dearcadh, cuirtear na hargóintí san URL chuig an modh ``get_object () ``in éineacht leis an réad iarratais.

Seo an cód do na fothaí seo a bhaineann go sonrach le bualadh:

Code
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]

Chun ``, ``, agus <title>```` an bheatha <link>a ghiniúint, <description>úsáideann Django na modhanna `teideal () ``, link () agus ```cur síos (). Sa sampla roimhe seo, ba tréithe aicme teaghráin iad, ach léiríonn an sampla seo gur féidir leo a bheith ina mhodhanna teaghráin* nó*. I gcás gach ceann de teideal ``, `nasc agus tuairisc, leanann Django an algartam seo:

  • Ar dtús, déanann sé iarracht modh a ghlaoch, ag dul ar an argóint obj ``, áit a bhfuil `obj an rud a chuir ar ais ag ``get_object () ``.

  • Má theipeann sé sin, déanann sé iarracht modh a ghlaoch gan aon argóintí.

  • Mura n-úsáideann sé sin, úsáideann sé an tréith ranga.

Tabhair faoi deara freisin go leanann items () ``an algartam céanna freisin -- ar dtús, déanann iarracht ``items (obj), ansin items (), ansin ar deireadh tréith aicme ``earraí ``(ba chóir a bheith ina liosta).

Táimid ag úsáid teimpléad do na tuairiscí earraí. Is féidir leis a bheith chomh íosta leis seo:

Django template
{{ obj.description }}

Mar sin féin, tá saor ort formáidiú a chur leis de réir mar is mian leat.

Tugann an rang ExampleFeed thíos doiciméadú iomlán ar mhodhanna agus tréithe ranganna: Class: ~Django.Contrib.Syndication.Views.Feed.

An cineál beatha a shonrúLink to this heading

De réir réamhshocraithe, úsáideann fothaí a tháirgtear sa chreat seo RSS 2.0.

Chun é sin a athrú, cuir tréith feed_type le d'aicme:class: ~django.contrib.syndication.views.feed, mar sin:

Code
from django.utils.feedgenerator import Atom1Feed


class MyFeed(Feed):
    feed_type = Atom1Feed

Tabhair faoi deara go socraíonn tú feed_type le réad aicme, ní sampla.

Is iad na cineálacha beatha atá ar fáil faoi láthair:

IomláinLink to this heading

Chun imfhálacha a shonrú, amhail na cinn a úsáidtear chun fothaí podchraolta a chruthú, bain úsáid as an crúca item_enclosure nó, mura bhfuil ach imfhálú amháin agat in aghaidh an earra, na crúcaí item_enclosure_url ``, `item_enclosure_mime_type. Féach an rang ExampleFeed thíos le haghaidh samplaí úsáide.

TeangaLink to this heading

I measc na bhfothaí a chruthaíonn an creat sindiciúcháin go huathoibríoch tá an chlib <language> cuí (RSS 2.0) nó xml: lang tréith (Atom). De réir réamhshocraithe, is é seo: func: `django.utils.translation.get_language () `. Is féidir leat é a athrú tríd an tréith aicme ``teanga ``a shocrú.

URLannaLink to this heading

Is féidir leis an modh/tréith nasc cosán iomlán a thabhairt ar ais (m.sh. /blog/") nó URL leis an bhfearann agus an prótacal láncháilithe (m.sh.``” https://www.example.com/blog/). <SITE_ID>Mura bhfilleann ``nasc an fearann ar ais, cuirfidh an creat siondicíochta fearann an láithreáin reatha isteach, de réir do shuíomh: `SET_ID `.

Teastaíonn <link rel="self">```` i bhfothaí Atom a shainmhíníonn suíomh reatha an bheatha. Déanann an creat siondála é seo a líonadh go huathoibríoch, ag baint úsáide as fearann an láithreáin reatha de réir an shocraithe:setting: SITE_ID.

Fothaí Atom agus RSS a fhoilsiú in éineachtLink to this heading

Is maith le roinnt forbróirí leaganacha Atom* agus* RSS dá bhfothaí a chur ar fáil. Chun sin a dhéanamh, is féidir leat fo-aicme de do rang: ~django.contrib.syndication.views.feed a chruthú agus an feed_type` a shocrú go rud éigin difriúil. Ansin nuashonraigh do URLConf chun na leaganacha breise a chur leis.

Seo sampla iomlán:

Code
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

Agus an URLConf a ghabhann leis:

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

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

Tagairt aicme FeedLink to this heading

class views.FeedLink to this definition

Léiríonn an sampla seo gach tréithe agus modhanna féideartha d'aicme a:class: ~django.contrib.syndication.views.feed:

Code
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  # Hard coded value

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

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

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

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

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

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

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

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

    # ITEM AUTHOR LINK -- One of the following three is optional. The
    # framework looks for them in this order. In each case, the URL should
    # include the 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

An creat ar leibhéal ísealLink to this heading

Taobh thiar de na radhairc, úsáideann an creat ardleibhéil RSS creat leibhéal níos ísle chun XML fothaí a ghiniúint. Tá an creat seo ina gcónaí i modúl amháin: :source: django/utils/feedgenerator.py.

Úsáideann tú an creat seo leat féin, le haghaidh giniúint beatha ar leibhéal níos ísle. Is féidir leat fo-aicmí gineadóir beatha saincheaptha a chruthú freisin le húsáid leis an rogha feed_type Feed `.

Ranganna SyndicationFeedLink to this heading

Tá bunaicme sa mhodúl:MOD: ~django.utils.feedgenerator:

agus roinnt fo-aicmí:

Tá a fhios ag gach ceann de na trí rang seo conas cineál áirithe beatha a rinneadh mar XML. Roinneann siad an comhéadan seo:

SyndicationFeed.__init__()

Cuir tús leis an bhfoclóir meiteashonraí a thugtar, a bhaineann leis an mbeatha iomlán. Argóintí eochairfhocal riachtanacha

  • ``teideal ``

  • nasc

  • `Tuairisc

Tá dornán eochairfhocail roghnacha eile ann freisin:

  • teanga

  • `Author_Ríomhphost

  • ainm_údar

  • nasc_údar

  • ``fotheidil ``

  • Catagóirí

  • ``feed_url ``

  • feed_copyright

  • treoir_feed

  • ttl

  • stylesheets

Stórálfar aon argóintí eochairfhocal breise a chuireann tú chuig __init__ i self.feed ``le húsáid le `gineadóirí beatha saincheapaithe.

All parameters should be strings, except for two:

  • Ba chóir go mbeadh “catagóirí” ina seicheamh teaghráin.

  • stylesheets should be a sequence of either strings or Stylesheet instances.

Beware that some control characters are not allowed in XML documents. If your content has some of them, you might encounter a ValueError when producing the feed.

SyndicationFeed.add_item()

Cuir mír leis an mbeatha leis na paraiméadair a thugtar.

Argóintí eochairfhocal riachtanacha

  • ``teideal ``

  • nasc

  • `Tuairisc

Argóintí eochairfhocal roghnacha

  • `Author_Ríomhphost

  • ainm_údar

  • nasc_údar

  • ``Pubdáta`

  • ``Tráchtaireachtaí ``

  • ``Unique_id ``

  • Enclósurs

  • Catagóirí

  • ear_copyright

  • ttl

  • Dáta nuashonraithe

Stórálfar argóintí eochairfhocal breise do gineadóirí beatha saincheapaithe.

Ba chóir go mbeadh na paraiméadair go léir, má thugtar, a bheith ina teaghrá

  • Ba chóir go mbeadh pubdate` ina réad Python: Class: ~datetime.datetime.

  • Ba chóir go mbeadh updateddate` ina réad Python: Class: ~datetime.datetime.

  • Ba chóir go mbeadh enclosures liosta de:class: django.utils.feedgenerator.enclosure cásanna.

  • Ba chóir go mbeadh “catagóirí” ina seicheamh teaghráin.

SyndicationFeed.write()

Aisíonn sé an beatha san ionchódú a thugtar chun outfile, ar réad cosúil le comhad é.

SyndicationFeed.writeString()

Tugann sé an beatha ar ais mar shreang san ionchódú a thugtar.

Mar shampla, chun beatha Atom 1.0 a chruthú agus é a phriontáil chuig aschur caighdeánach:

Python console
>>> 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>

Gineadóirí beatha saincheapthaLink to this heading

Más gá duit formáid beatha saincheaptha a tháirgeadh, tá cúpla rogha agat.

Má tá an fhormáid beatha go hiomlán saincheaptha, beidh tú ag iarraidh “SyndicationFeed” a fho-aicmiú agus na modhanna write () ``agus `WriteString () a chur in ionad go hiomlán.

Mar sin féin, más spin-off de RSS nó Atom é an fhormáid beatha (ie GeoRSS, formáid podchraoladh “iTunes” _ Apple, srl.), Tá rogha níos fearr agat. De ghnáth cuireann na cineálacha fothaí seo eilimintí agus/nó tréithe breise leis an bhformáid bhunúsach, agus tá sraith modhanna ann a ghlaonn SyndicationFeed chun na tréithe breise seo a fháil. Dá bhrí sin, is féidir leat an rang gineadóir beatha cuí a fho-aicmiú (Atom1FeedRSS201REV2Feed) agus na haisghlaonna seo a leathnú. Is iad seo a leanas:

``SyndicationFeed.root_attributs (féin) ``

Tabhair ar ais dict de thréithe le cur leis an eilimint beatha fréimhe (feed`/chainel).

``SyndicationFeed.Add_Root_Elements (féin, láimhseálaí) ``

Glaoigh ar ais chun eilimintí a chur leis taobh istigh den eilimint beatha fréimhe (feed``/channel ``). Is é ``handler an:class: ~xml.sax.saxutils.xmlGenerator ó leabharlann SAX ionsuite Python; glaoifidh tú modhanna air chun cur leis an doiciméad XML atá i bpróiseas.

``SyndicationFeed.Item_Attributes (féin, mír) ``

Tabhair ar ais dict de thréithe le cur le gach mír (ear/iontrála) eilimint. Is foclóir é an argóint, Item `, de na sonraí go léir a chuirtear chuig SyndicationFeed.add_item ()`.

``SyndicationFeed.Add_Item_Elements (féin, láimhseálaí, mír) ``

Glaoigh ar ais chun eilimintí a chur le gach eilimint (item/iontrála`). ``handler agus ear mar atá thuas.

Mar shampla, b'fhéidir go dtosóidh tú gineadóir beatha iTunes RSS a chur i bhfeidhm mar seo:

Code
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")

Tá a lán níos mó oibre le déanamh le haghaidh rang beatha saincheaptha iomlán, ach ba cheart go léireodh an sampla thuas an bunsmaoineamh.

Feed stylesheetsLink to this heading

If you wish to have your RSS feed render nicely in a browser, you will need to provide styling information for the XML file, typically in XSLT or CSS formats.

You can add this to your RSS feed by setting the stylesheets attribute on the feed class.

This can be a hardcoded URL:

Code
from django.contrib.syndication.views import Feed


class FeedWithHardcodedStylesheet(Feed):
    stylesheets = [
        "https://example.com/rss_stylesheet.xslt",
    ]

You can also use Django's static files system:

Code
from django.contrib.syndication.views import Feed
from django.templatetags.static import static


class FeedWithStaticFileStylesheet(Feed):
    stylesheets = [
        static("rss_styles.xslt"),
    ]

Another option is to have a view in your project that renders the XSLT document. You can then link it like so:

Code
from django.contrib.syndication.views import Feed
from django.urls import reverse_lazy


class FeedWithStylesheetView(Feed):
    stylesheets = [
        reverse_lazy("your-custom-view-name"),
    ]

Django will normally try to guess the MIME type of the given URL based on its extension, but if that fails you can specify it using the Stylesheet class:

Code
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"),
    ]

Similarly, if you'd like to use a different media attribute than screen (Django's default), you can use the Stylesheet class again:

Code
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"),
    ]

Any of these options can be combined when using multiple stylesheets:

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


class MultiStylesheetFeed(Feed):
    stylesheets = [
        "/stylesheet1.xsl",
        Stylesheet("/stylesheet2.xsl"),
    ]