| 1 |
from inspect import getattr_static, unwrap |
| 2 |
|
| 3 |
from django.contrib.sites.shortcuts import get_current_site |
| 4 |
from django.core.exceptions import ImproperlyConfigured, ObjectDoesNotExist |
| 5 |
from django.http import Http404, HttpResponse |
| 6 |
from django.template import TemplateDoesNotExist, loader |
| 7 |
from django.utils import feedgenerator |
| 8 |
from django.utils.encoding import iri_to_uri |
| 9 |
from django.utils.html import escape |
| 10 |
from django.utils.http import http_date |
| 11 |
from django.utils.timezone import get_default_timezone, is_naive, make_aware |
| 12 |
from django.utils.translation import get_language |
| 13 |
|
| 14 |
|
| 15 |
def add_domain(domain, url, secure=False): |
| 16 |
protocol = "https" if secure else "http" |
| 17 |
if url.startswith("//"): |
| 18 |
# Support network-path reference (see #16753) - RSS requires a protocol |
| 19 |
url = "%s:%s" % (protocol, url) |
| 20 |
elif not url.startswith(("http://", "https://", "mailto:")): |
| 21 |
url = iri_to_uri("%s://%s%s" % (protocol, domain, url)) |
| 22 |
return url |
| 23 |
|
| 24 |
|
| 25 |
class FeedDoesNotExist(ObjectDoesNotExist): |
| 26 |
pass |
| 27 |
|
| 28 |
|
| 29 |
class Feed: |
| 30 |
feed_type = feedgenerator.DefaultFeed |
| 31 |
title_template = None |
| 32 |
description_template = None |
| 33 |
language = None |
| 34 |
|
| 35 |
def __call__(self, request, *args, **kwargs): |
| 36 |
try: |
| 37 |
obj = self.get_object(request, *args, **kwargs) |
| 38 |
except ObjectDoesNotExist: |
| 39 |
raise Http404("Feed object does not exist.") |
| 40 |
feedgen = self.get_feed(obj, request) |
| 41 |
response = HttpResponse(content_type=feedgen.content_type) |
| 42 |
if hasattr(self, "item_pubdate") or hasattr(self, "item_updateddate"): |
| 43 |
# if item_pubdate or item_updateddate is defined for the feed, set |
| 44 |
# header so as ConditionalGetMiddleware is able to send 304 NOT MODIFIED |
| 45 |
response.headers["Last-Modified"] = http_date( |
| 46 |
feedgen.latest_post_date().timestamp() |
| 47 |
) |
| 48 |
feedgen.write(response, "utf-8") |
| 49 |
return response |
| 50 |
|
| 51 |
def item_title(self, item): |
| 52 |
# Titles should be double escaped by default (see #6533) |
| 53 |
return escape(str(item)) |
| 54 |
|
| 55 |
def item_description(self, item): |
| 56 |
return str(item) |
| 57 |
|
| 58 |
def item_link(self, item): |
| 59 |
try: |
| 60 |
return item.get_absolute_url() |
| 61 |
except AttributeError: |
| 62 |
raise ImproperlyConfigured( |
| 63 |
"Give your %s class a get_absolute_url() method, or define an " |
| 64 |
"item_link() method in your Feed class." % item.__class__.__name__ |
| 65 |
) |
| 66 |
|
| 67 |
def item_enclosures(self, item): |
| 68 |
enc_url = self._get_dynamic_attr("item_enclosure_url", item) |
| 69 |
if enc_url: |
| 70 |
enc = feedgenerator.Enclosure( |
| 71 |
url=str(enc_url), |
| 72 |
length=str(self._get_dynamic_attr("item_enclosure_length", item)), |
| 73 |
mime_type=str(self._get_dynamic_attr("item_enclosure_mime_type", item)), |
| 74 |
) |
| 75 |
return [enc] |
| 76 |
return [] |
| 77 |
|
| 78 |
def _get_dynamic_attr(self, attname, obj, default=None): |
| 79 |
try: |
| 80 |
attr = getattr(self, attname) |
| 81 |
except AttributeError: |
| 82 |
return default |
| 83 |
if callable(attr): |
| 84 |
# Check co_argcount rather than try/excepting the function and |
| 85 |
# catching the TypeError, because something inside the function |
| 86 |
# may raise the TypeError. This technique is more accurate. |
| 87 |
func = unwrap(attr) |
| 88 |
try: |
| 89 |
code = func.__code__ |
| 90 |
except AttributeError: |
| 91 |
func = unwrap(attr.__call__) |
| 92 |
code = func.__code__ |
| 93 |
# If function doesn't have arguments and it is not a static method, |
| 94 |
# it was decorated without using @functools.wraps. |
| 95 |
if not code.co_argcount and not isinstance( |
| 96 |
getattr_static(self, func.__name__, None), staticmethod |
| 97 |
): |
| 98 |
raise ImproperlyConfigured( |
| 99 |
f"Feed method {attname!r} decorated by {func.__name__!r} needs to " |
| 100 |
f"use @functools.wraps." |
| 101 |
) |
| 102 |
if code.co_argcount == 2: # one argument is 'self' |
| 103 |
return attr(obj) |
| 104 |
else: |
| 105 |
return attr() |
| 106 |
return attr |
| 107 |
|
| 108 |
def feed_extra_kwargs(self, obj): |
| 109 |
""" |
| 110 |
Return an extra keyword arguments dictionary that is used when |
| 111 |
initializing the feed generator. |
| 112 |
""" |
| 113 |
return {} |
| 114 |
|
| 115 |
def item_extra_kwargs(self, item): |
| 116 |
""" |
| 117 |
Return an extra keyword arguments dictionary that is used with |
| 118 |
the `add_item` call of the feed generator. |
| 119 |
""" |
| 120 |
return {} |
| 121 |
|
| 122 |
def get_object(self, request, *args, **kwargs): |
| 123 |
return None |
| 124 |
|
| 125 |
def get_context_data(self, **kwargs): |
| 126 |
""" |
| 127 |
Return a dictionary to use as extra context if either |
| 128 |
``self.description_template`` or ``self.item_template`` are used. |
| 129 |
|
| 130 |
Default implementation preserves the old behavior |
| 131 |
of using {'obj': item, 'site': current_site} as the context. |
| 132 |
""" |
| 133 |
return {"obj": kwargs.get("item"), "site": kwargs.get("site")} |
| 134 |
|
| 135 |
def get_feed(self, obj, request): |
| 136 |
""" |
| 137 |
Return a feedgenerator.DefaultFeed object, fully populated, for |
| 138 |
this feed. Raise FeedDoesNotExist for invalid parameters. |
| 139 |
""" |
| 140 |
current_site = get_current_site(request) |
| 141 |
|
| 142 |
link = self._get_dynamic_attr("link", obj) |
| 143 |
link = add_domain(current_site.domain, link, request.is_secure()) |
| 144 |
|
| 145 |
feed = self.feed_type( |
| 146 |
title=self._get_dynamic_attr("title", obj), |
| 147 |
subtitle=self._get_dynamic_attr("subtitle", obj), |
| 148 |
link=link, |
| 149 |
description=self._get_dynamic_attr("description", obj), |
| 150 |
language=self.language or get_language(), |
| 151 |
feed_url=add_domain( |
| 152 |
current_site.domain, |
| 153 |
self._get_dynamic_attr("feed_url", obj) or request.path, |
| 154 |
request.is_secure(), |
| 155 |
), |
| 156 |
author_name=self._get_dynamic_attr("author_name", obj), |
| 157 |
author_link=self._get_dynamic_attr("author_link", obj), |
| 158 |
author_email=self._get_dynamic_attr("author_email", obj), |
| 159 |
categories=self._get_dynamic_attr("categories", obj), |
| 160 |
feed_copyright=self._get_dynamic_attr("feed_copyright", obj), |
| 161 |
feed_guid=self._get_dynamic_attr("feed_guid", obj), |
| 162 |
ttl=self._get_dynamic_attr("ttl", obj), |
| 163 |
stylesheets=self._get_dynamic_attr("stylesheets", obj), |
| 164 |
**self.feed_extra_kwargs(obj), |
| 165 |
) |
| 166 |
|
| 167 |
title_tmp = None |
| 168 |
if self.title_template is not None: |
| 169 |
try: |
| 170 |
title_tmp = loader.get_template(self.title_template) |
| 171 |
except TemplateDoesNotExist: |
| 172 |
pass |
| 173 |
|
| 174 |
description_tmp = None |
| 175 |
if self.description_template is not None: |
| 176 |
try: |
| 177 |
description_tmp = loader.get_template(self.description_template) |
| 178 |
except TemplateDoesNotExist: |
| 179 |
pass |
| 180 |
|
| 181 |
for item in self._get_dynamic_attr("items", obj): |
| 182 |
context = self.get_context_data( |
| 183 |
item=item, site=current_site, obj=obj, request=request |
| 184 |
) |
| 185 |
if title_tmp is not None: |
| 186 |
title = title_tmp.render(context, request) |
| 187 |
else: |
| 188 |
title = self._get_dynamic_attr("item_title", item) |
| 189 |
if description_tmp is not None: |
| 190 |
description = description_tmp.render(context, request) |
| 191 |
else: |
| 192 |
description = self._get_dynamic_attr("item_description", item) |
| 193 |
link = add_domain( |
| 194 |
current_site.domain, |
| 195 |
self._get_dynamic_attr("item_link", item), |
| 196 |
request.is_secure(), |
| 197 |
) |
| 198 |
enclosures = self._get_dynamic_attr("item_enclosures", item) |
| 199 |
author_name = self._get_dynamic_attr("item_author_name", item) |
| 200 |
if author_name is not None: |
| 201 |
author_email = self._get_dynamic_attr("item_author_email", item) |
| 202 |
author_link = self._get_dynamic_attr("item_author_link", item) |
| 203 |
else: |
| 204 |
author_email = author_link = None |
| 205 |
|
| 206 |
tz = get_default_timezone() |
| 207 |
|
| 208 |
pubdate = self._get_dynamic_attr("item_pubdate", item) |
| 209 |
if pubdate and is_naive(pubdate): |
| 210 |
pubdate = make_aware(pubdate, tz) |
| 211 |
|
| 212 |
updateddate = self._get_dynamic_attr("item_updateddate", item) |
| 213 |
if updateddate and is_naive(updateddate): |
| 214 |
updateddate = make_aware(updateddate, tz) |
| 215 |
|
| 216 |
feed.add_item( |
| 217 |
title=title, |
| 218 |
link=link, |
| 219 |
description=description, |
| 220 |
unique_id=self._get_dynamic_attr("item_guid", item, link), |
| 221 |
unique_id_is_permalink=self._get_dynamic_attr( |
| 222 |
"item_guid_is_permalink", item |
| 223 |
), |
| 224 |
enclosures=enclosures, |
| 225 |
pubdate=pubdate, |
| 226 |
updateddate=updateddate, |
| 227 |
author_name=author_name, |
| 228 |
author_email=author_email, |
| 229 |
author_link=author_link, |
| 230 |
comments=self._get_dynamic_attr("item_comments", item), |
| 231 |
categories=self._get_dynamic_attr("item_categories", item), |
| 232 |
item_copyright=self._get_dynamic_attr("item_copyright", item), |
| 233 |
**self.item_extra_kwargs(item), |
| 234 |
) |
| 235 |
return feed |