Commits

Juan Martínez  committed b5c760f

Feed support (Atom) using Django's syndication feed framework.

  • Participants
  • Parent commits b8d79ef

Comments (0)

Files changed (6)

File pyweek/challenge/models.py

 from django.core import validators
 from django.db import models, connection, transaction
 from django.contrib.auth.models import User
+from django.core.urlresolvers import reverse
 
 from stripogram import html2text
 import datetime
             self.activity = datetime.datetime.utcnow()
         super(DiaryEntry, self).save()
 
+    def get_absolute_url(self):
+        return reverse("pyweek.challenge.views.message.diary_display", args=[self.id])
+
 class DiaryComment(models.Model):
     challenge = models.ForeignKey(Challenge, blank=True, null=True)
     diary_entry = models.ForeignKey(DiaryEntry)

File pyweek/challenge/templates/base.html

     <link rel="stylesheet" href="{{ STATIC_URL }}challenge.css" type="text/css">
     <link rel="alternate" type="application/rss+xml"
        title="PyWeek Diaries RSS feed"
-       href="{{ MEDIA_URL }}rss/diaries.rss">
+       href="{% url diary_feed %}">
        <script src="{{ STATIC_URL }}js/challenge.js" type="text/javascript"></script>
        <script src="{{ STATIC_URL }}js/jquery.min.js" type="text/javascript"></script>
     {% block links %}

File pyweek/challenge/templates/diary_entries.html

 {% endfor %}
 </div>
 
+

File pyweek/challenge/templates/messages.html

 
 {% block content %}
 
-<p style="margin-top: 0px;"><a class="add" href="/message_add/">Post new message</a></p>
+<p style="margin-top: 0px; text-align: right;"><span style="float:left;"><a class="add" href="/message_add/">Post new message</a></span> <a class="button" href="{% url diary_feed %}">Atom Feed</a></p>
 
 <table id="diary-board">
 <tr><th>Message</th><!-- th>Team</th --><th>Rep</th><th>Last Post</th></tr>
 {% endif %}
 </td></tr>
 </table>
-
 {% endblock %}
-

File pyweek/challenge/urls.py

 from django.conf.urls.defaults import *
 #from django.conf.settings import DEBUG
+from pyweek.challenge.views.message import DiaryFeed
 
 urlpatterns = patterns('pyweek.challenge.views.challenge',
     (r'^/?$', 'index'),
     (r'^d/(\d+)/edit/$', 'diary_edit'),
     (r'^d/(\d+)/delete/$', 'diary_delete'),
     (r'^e/([\w-]+)/diary/$', 'entry_diary'),
+    url(r'^d/feed/$', DiaryFeed(), name='diary_feed'),
 )
 
 urlpatterns += patterns('pyweek.challenge.views.user',

File pyweek/challenge/views/message.py

 
 from django import forms
 from django.contrib import messages
+from django.contrib.syndication.views import Feed
 from django.shortcuts import render_to_response, get_object_or_404
 from django.template import RequestContext
 from django.http import HttpResponse, HttpResponseRedirect
                 diary.sticky = form.cleaned_data.get('sticky', False)
             diary.created = datetime.datetime.utcnow()
             diary.save()
-            generate_diary_rss()
             messages.success(request, 'Entry saved!')
             return HttpResponseRedirect('/d/%s/'%diary.id)
     else:
             if is_super:
                 diary.sticky = form.cleaned_data.get('sticky', False)
             diary.save()
-            generate_diary_rss()
             messages.success(request, 'Entry saved!')
             return HttpResponseRedirect('/d/%s/'%diary.id)
     else:
             'is_owner': entry.user == request.user,
         }, context_instance=RequestContext(request))
 
-feed_template = u'''<?xml version="1.0" encoding="UTF-8" standalone="no"?>
-<rss version="2.0">
- <channel>
-  <title>PyWeek Diary Entries</title>
-  <link>http://pyweek.org/</link>
-  <description>The latest 40 entries from diaries at the
-  PyWeek challenge</description>
-  <managingEditor>richard@pyweek.org (Richard Jones)</managingEditor>
-  <language>en</language>
-  %(items)s
- </channel>
-</rss>
-'''
+class DiaryFeed(Feed):
+    title = "PyWeek Diary Entries"
+    link = "/"
+    description = "The latest 40 entries from diaries at the PyWeek challenge."
 
-item_template = u'''
-  <item>
-   <title>%(title)s</title>
-   <pubDate>%(date)s</pubDate>
-   <link>%(url)s</link>
-   <guid>%(url)s</guid>
-   <description>%(content)s&lt;br&gt;-- %(author)s</description>
-  </item>
-'''
+    def items(self):
+        return models.DiaryEntry.objects.order_by('-created')[:40]
 
-def unicode_god_damnit(s):
-    if isinstance(s, str):
-        try:
-            s = s.decode('utf8')
-        except UnicodeDecodeError:
-            s = s.decode('ascii', 'replace')
-    return s
+    def item_title(self, item):
+        return item.title
 
-def generate_diary_rss():
-    l = []
-    e = xml.sax.saxutils.escape
-    for diary in models.DiaryEntry.objects.\
-            filter(is_pyggy=False).order_by('-created')[:40]:
-        entry = diary.entry
-        title = cgi.escape(unicode_god_damnit(diary.title))
-        if entry:
-            s = unicode_god_damnit(entry.title)
-            author = cgi.escape('%s of <a href="http://pyweek.org/e/%s/">%s</a>'%(
-                diary.user, entry.name, e(s)))
-        else:
-            author = cgi.escape(str(diary.user))
-        url = 'http://pyweek.org/d/%s/'%diary.id
-        date = diary.created.strftime("%a, %d %b %Y %H:%M:%S -0600")
-        content = cgi.escape(unicode_god_damnit(diary.content))
-        l.append(item_template%locals())
-    items = '\n'.join(l)
-    f = open(settings.DIARY_RSS_FILE_NEW, 'w')
-    f.write((feed_template%locals()).encode('utf8'))
-    f.close()
-    os.rename(settings.DIARY_RSS_FILE_NEW, settings.DIARY_RSS_FILE)
+    def item_author_name(self, item):
+        return str(item.user)
+
+    def item_description(self, item):
+        return item.content
+
+    def item_pubdate(self, item):
+        return item.created
 
 class CommentForm(forms.Form):
     content = SafeHTMLField(required=True)
 
     if request.POST and 'delete' in request.POST:
         diary.delete()
-        generate_diary_rss()
         messages.success(request, "Diary entry deleted!")
         return HttpResponseRedirect('/e/%s/'%diary.entry_id)
     else: