Skip to content

Commit

Permalink
Fixed django#12978 -- Added support for RSS feed stylesheets.
Browse files Browse the repository at this point in the history
  • Loading branch information
bmispelon authored and sarahboyce committed Jun 18, 2024
1 parent ce1ad98 commit 62300b8
Show file tree
Hide file tree
Showing 9 changed files with 388 additions and 8 deletions.
1 change: 1 addition & 0 deletions django/contrib/syndication/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,7 @@ def get_feed(self, obj, request):
feed_copyright=self._get_dynamic_attr("feed_copyright", obj),
feed_guid=self._get_dynamic_attr("feed_guid", obj),
ttl=self._get_dynamic_attr("ttl", obj),
stylesheets=self._get_dynamic_attr("stylesheets", obj),
**self.feed_extra_kwargs(obj),
)

Expand Down
74 changes: 74 additions & 0 deletions django/utils/feedgenerator.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@

import datetime
import email
import mimetypes
from io import StringIO
from urllib.parse import urlparse

Expand Down Expand Up @@ -57,6 +58,53 @@ def get_tag_uri(url, date):
return "tag:%s%s:%s/%s" % (bits.hostname, d, bits.path, bits.fragment)


def _guess_stylesheet_mimetype(url):
"""
Return the given stylesheet's mimetype tuple, using a slightly custom
version of Python's mimetypes.guess_type().
"""
mimetypedb = mimetypes.MimeTypes()

# The official mimetype for XSLT files is technically `application/xslt+xml`
# but as of 2024 almost no browser supports that (they all expect text/xsl).
# On top of that, windows seems to assume that the type for xsl is text/xml.
mimetypedb.readfp(StringIO("text/xsl\txsl\ntext/xsl\txslt"))

return mimetypedb.guess_type(url)


class Stylesheet:
"""An RSS stylesheet"""

def __init__(self, url, mimetype="", media="screen"):
self._url = url
self._mimetype = mimetype
self.media = media

# Using a property to delay the evaluation of self._url as late as possible
# in case of a lazy object (like reverse_lazy(...) for example).
@property
def url(self):
return iri_to_uri(self._url)

@property
def mimetype(self):
if self._mimetype == "":
return _guess_stylesheet_mimetype(self.url)[0]
return self._mimetype

def __str__(self):
data = [f'href="{self.url}"']
if self.mimetype is not None:
data.append(f'type="{self.mimetype}"')
if self.media is not None:
data.append(f'media="{self.media}"')
return " ".join(data)

def __repr__(self):
return repr((self.url, self.mimetype, self.media))


class SyndicationFeed:
"Base class for all syndication feeds. Subclasses should provide write()"

Expand All @@ -75,12 +123,24 @@ def __init__(
feed_copyright=None,
feed_guid=None,
ttl=None,
stylesheets=None,
**kwargs,
):
def to_str(s):
return str(s) if s is not None else s

def to_stylesheet(s):
return s if isinstance(s, Stylesheet) else Stylesheet(s)

categories = categories and [str(c) for c in categories]

if stylesheets is not None:
if isinstance(stylesheets, (Stylesheet, str)):
raise TypeError(
f"stylesheets should be a list, not {stylesheets.__class__}"
)
stylesheets = [to_stylesheet(s) for s in stylesheets]

self.feed = {
"title": to_str(title),
"link": iri_to_uri(link),
Expand All @@ -95,6 +155,7 @@ def to_str(s):
"feed_copyright": to_str(feed_copyright),
"id": feed_guid or link,
"ttl": to_str(ttl),
"stylesheets": stylesheets,
**kwargs,
}
self.items = []
Expand Down Expand Up @@ -166,6 +227,12 @@ def add_root_elements(self, handler):
"""
pass

def add_stylesheets(self, handler):
"""
Add stylesheet(s) to the feed. Called from write().
"""
pass

def item_attributes(self, item):
"""
Return extra attributes to place on each item (i.e. item/entry) element.
Expand Down Expand Up @@ -228,6 +295,9 @@ class RssFeed(SyndicationFeed):
def write(self, outfile, encoding):
handler = SimplerXMLGenerator(outfile, encoding, short_empty_elements=True)
handler.startDocument()
# Any stylesheet must come after the start of the document but before any tag.
# https://www.w3.org/Style/styling-XML.en.html
self.add_stylesheets(handler)
handler.startElement("rss", self.rss_attributes())
handler.startElement("channel", self.root_attributes())
self.add_root_elements(handler)
Expand All @@ -247,6 +317,10 @@ def write_items(self, handler):
self.add_item_elements(handler, item)
handler.endElement("item")

def add_stylesheets(self, handler):
for stylesheet in self.feed["stylesheets"] or []:
handler.processingInstruction("xml-stylesheet", stylesheet)

def add_root_elements(self, handler):
handler.addQuickElement("title", self.feed["title"])
handler.addQuickElement("link", self.feed["link"])
Expand Down
123 changes: 119 additions & 4 deletions docs/ref/contrib/syndication.txt
Original file line number Diff line number Diff line change
Expand Up @@ -596,6 +596,24 @@ This example illustrates all possible attributes and methods for a

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.

Expand Down Expand Up @@ -961,16 +979,26 @@ They share this interface:
* ``feed_copyright``
* ``feed_guid``
* ``ttl``
* ``stylesheets``

Any extra keyword arguments you pass to ``__init__`` will be stored in
``self.feed`` for use with `custom feed generators`_.

All parameters should be strings, except ``categories``, which should be a
sequence of strings. Beware that some control characters
are `not allowed <https://www.w3.org/International/questions/qa-controls>`_
in XML documents. If your content has some of them, you might encounter a
All parameters should be strings, except for two:

* ``categories`` should be a sequence of strings.
* ``stylesheets`` should be a sequence of either strings or
:class:`~django.utils.feedgenerator.Stylesheet` instances.

Beware that some control characters are
`not allowed <https://www.w3.org/International/questions/qa-controls>`_ in
XML documents. If your content has some of them, you might encounter a
:exc:`ValueError` when producing the feed.

.. versionchanged:: 5.2

The ``stylesheets`` argument was added.

:meth:`.SyndicationFeed.add_item`
Add an item to the feed with the given parameters.

Expand Down Expand Up @@ -1095,3 +1123,90 @@ For example, you might start implementing an iTunes RSS feed generator like so::

There's a lot more work to be done for a complete custom feed class, but the
above example should demonstrate the basic idea.

.. _feed-stylesheets:

Feed stylesheets
----------------

.. versionadded:: 5.2

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::

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::

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::

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
:class:`~django.utils.feedgenerator.Stylesheet` class::

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
:class:`~django.utils.feedgenerator.Stylesheet` class again::

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::

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


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

.. _xslt: https://developer.mozilla.org/en-US/docs/Web/XSLT/Transforming_XML_with_XSLT
46 changes: 43 additions & 3 deletions docs/ref/utils.txt
Original file line number Diff line number Diff line change
Expand Up @@ -331,6 +331,32 @@ https://web.archive.org/web/20110718035220/http://diveintomark.org/archives/2004

See https://web.archive.org/web/20110514113830/http://diveintomark.org/archives/2004/05/28/howto-atom-id

``Stylesheet``
--------------

.. versionadded:: 5.2

.. class:: Stylesheet(url, mimetype="", media="screen")

Represents an RSS stylesheet.

.. attribute:: url

Required argument. The URL where the stylesheet is located.

.. attribute:: mimetype

An optional string containing the MIME type of the stylesheet. If not
specified, Django will attempt to guess it by using Python's
:py:func:`mimetypes.guess_type()`. Use ``mimetype=None`` if you don't
want your stylesheet to have a MIME type specified.

.. attribute:: media

An optional string which will be used as the ``media`` attribute of
the stylesheet. Defaults to ``"screen"``. Use ``media=None`` if you
don't want your stylesheet to have a ``media`` attribute.

``SyndicationFeed``
-------------------

Expand All @@ -339,16 +365,23 @@ https://web.archive.org/web/20110718035220/http://diveintomark.org/archives/2004
Base class for all syndication feeds. Subclasses should provide
``write()``.

.. method:: __init__(title, link, description, language=None, author_email=None, author_name=None, author_link=None, subtitle=None, categories=None, feed_url=None, feed_copyright=None, feed_guid=None, ttl=None, **kwargs)
.. method:: __init__(title, link, description, language=None, author_email=None, author_name=None, author_link=None, subtitle=None, categories=None, feed_url=None, feed_copyright=None, feed_guid=None, ttl=None, stylesheets=None, **kwargs)

Initialize the feed with the given dictionary of metadata, which applies
to the entire feed.

Any extra keyword arguments you pass to ``__init__`` will be stored in
``self.feed``.

All parameters should be strings, except ``categories``, which should
be a sequence of strings.
All parameters should be strings, except for two:

* ``categories`` should be a sequence of strings.
* ``stylesheets`` should be a sequence of either strings or
:class:`Stylesheet` instances.

.. versionchanged:: 5.2

The ``stylesheets`` argument was added.

.. method:: add_item(title, link, description, author_email=None, author_name=None, author_link=None, pubdate=None, comments=None, unique_id=None, categories=(), item_copyright=None, ttl=None, updateddate=None, enclosures=None, **kwargs)

Expand All @@ -368,6 +401,13 @@ https://web.archive.org/web/20110718035220/http://diveintomark.org/archives/2004
Add elements in the root (i.e. feed/channel) element.
Called from ``write()``.

.. method:: add_stylesheets(self, handler)

.. versionadded:: 5.2

Add stylesheet information to the document.
Called from ``write()``.

.. method:: item_attributes(item)

Return extra attributes to place on each item (i.e. item/entry)
Expand Down
5 changes: 4 additions & 1 deletion docs/releases/5.2.txt
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,10 @@ Minor features
:mod:`django.contrib.syndication`
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

* ...
* All :class:`~django.utils.feedgenerator.SyndicationFeed` classes now support
a ``stylesheets`` attribute. If specified, an ``<? xml-stylesheet ?>``
processing instruction will be added to the top of the document for each
stylesheet in the given list. See :ref:`feed-stylesheets` for more details.

Asynchronous views
~~~~~~~~~~~~~~~~~~
Expand Down
7 changes: 7 additions & 0 deletions tests/syndication_tests/feeds.py
Original file line number Diff line number Diff line change
Expand Up @@ -236,6 +236,13 @@ def item_title(self, item):
return "Title: %s" % item.title


class TestFeedWithStylesheets(TestRss2Feed):
stylesheets = [
"/stylesheet1.xsl",
feedgenerator.Stylesheet("/stylesheet2.xsl"),
]


class NaiveDatesFeed(TestAtomFeed):
"""
A feed with naive (non-timezone-aware) dates.
Expand Down
Loading

0 comments on commit 62300b8

Please sign in to comment.