Source

Mango / feeds.py

Full commit
from django import http
from django.core.cache import cache
from django.utils import feedgenerator

import mango.settings
from mango.main import Index

def atom(request, tag=None):
    content_type = 'application/atom+xml; charset=utf-8'
    feed_url = request.build_absolute_uri()
    cache_key = 'mango:%s' % feed_url
    xml = cache.get(cache_key)
    if xml:
        return http.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: mango.settings.SITE_TITLE,
        'link':         lambda: mango.settings.BASE_URL,
        'description':  lambda: u'',  # required by constructor, but does not affect output
    }
    optional = {
        'author_name':  lambda: mango.settings.PRIMARY_AUTHOR_NAME,
        'author_email': lambda: mango.settings.PRIMARY_AUTHOR_EMAIL,
        'author_link':  lambda: mango.settings.PRIMARY_AUTHOR_URL,
        'feed_url':     lambda: feed_url,
        'feed_guid':    lambda: mango.settings.BASE_URL,
    }

    kwargs = all_kwargs(required, optional)

    if not kwargs:
        return http.HttpResponseServerError

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

    for post in Index.get().descendants():
        if (todo or all) and (tag is None or post.has_tag(tag)):
            required = {
                'title':       lambda: post.title_text,
                'link':        lambda: post.permalink(),
                'description': lambda: post.html,
            }
            optional = {
                'author_name': lambda: post.meta['author'],
                'pubdate':     lambda: post.datetime,
                'unique_id':   lambda: post.permalink(),
            }
            kwargs = all_kwargs(required, optional, post)
            if kwargs:
                feed.add_item(**kwargs)
                todo -= 1

    xml = feed.writeString('utf-8')
    cache.set(cache_key, xml, mango.settings.INDEX_CACHE_SECONDS)
    return http.HttpResponse(xml, content_type=content_type)