Source

Mango / feeds.py

Full commit
from django.core.cache import cache
from django.http import HttpResponse, HttpResponseServerError
from django.utils import feedgenerator
from mango import utils
from mango.settings import *

def atom(request):
    content_type = 'application/atom+xml; charset=utf-8'
    cache_key = feed_url = BASE_URL.rstrip('/') + request.META['PATH_INFO']
    xml = cache.get(cache_key)
    if xml:
        return HttpResponse(xml, content_type=content_type)

    def required_kwargs(required, post=None):
        try:
            return dict([key, function()] for key, function in required.items())
        except KeyError:
            return False

    def all_kwargs(required, optional, post=None):
        kwargs = required_kwargs(required, post)
        if not kwargs:
            return False
        for key, function in optional.items():
            try:
                value = function()
                if value: # don't include pair if its value is empty
                    kwargs[key] = value
            except KeyError:
                pass
        return kwargs

    required = {
        'title':        lambda: unicode(SITE_TITLE, 'utf-8'),
        'link':         lambda: unicode(BASE_URL, 'utf-8'),
        'description':  lambda: u'', # required by constructor, but does not affect output
    }
    optional = {
        'author_name':  lambda: unicode(PRIMARY_AUTHOR_NAME, 'utf-8'),
        'author_email': lambda: unicode(PRIMARY_AUTHOR_EMAIL, 'utf-8'),
        'author_link':  lambda: unicode(PRIMARY_AUTHOR_URL, 'utf-8'),
        'feed_url':     lambda: feed_url,
        'feed_guid':    lambda: unicode(BASE_URL, 'utf-8'),
    }

    kwargs = all_kwargs(required, optional)

    if not kwargs:
        return HttpResponseServerError

    feed = feedgenerator.Atom1Feed(**kwargs)
    todo = FEED_MAX_POSTS
    all = todo == 0

    for year, month, posts in utils.posts():
        for post in posts:
            if todo or all:
                required = {
                    'title':       lambda: post['meta']['title'],
                    'link':        lambda: post['meta']['url'],
                    'description': lambda: post['html'],
                }
                optional = {
                    'author_name': lambda: post['meta']['author'],
                    'pubdate':     lambda: post['meta']['datetime'],
                    'unique_id':   lambda: post['meta']['url'],
                }
                kwargs = all_kwargs(required, optional, post)
                if kwargs:
                    feed.add_item(**kwargs)
                    todo -= 1

    xml = feed.writeString('utf-8')
    cache.set(cache_key, xml, CACHE_SECONDS)
    return HttpResponse(xml, content_type=content_type)