Login

Media RSS generation for Photologue

Author:
ltvolks
Posted:
July 23, 2009
Language:
Python
Version:
1.0
Score:
2 (after 2 ratings)

Provides a basic implementation of Yahoo's MediaRSS format for Photologue galleries

Simplest usage: I have feedgenerator.py in a utils directory. Import photofeeds and hook up the feed url in your URLConf:

from utils.feedgenerator import photofeeds
urlpatterns += patterns('',
     url(r'^feeds/(?P<url>.*)/$', 'django.contrib.syndication.views.feed', {'feed_dict': photofeeds}),)

Without customization, this will generate a feed for the gallery archive at /feeds/gallery/ It will contain a single photo per gallery, as returned by Gallery.sample()

Additionally, each gallery has a dynamic feed available at the url via Gallery.title_slug: /feeds/gallery/gallery-title-slug/ This feed will contain an Item for each Photo in the Gallery

All that is left is to add an autodiscovery feed to your pages in &lt;head&gt;. An RSS agent like CoolIris can then parse your gallery and provide a slick view of your photos.

e.g Add something like this to gallery_detail.html:

<link rel="alternate" href="/feeds/gallery/{{ object.title_slug }}/" type="application/rss+xml" title="Photologue Gallery - {{ object.title }}" id="gallery_feed" />

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
"""feedgenerator.py
Provides basic Feed implementation for generating a MediaRSS feed for photologue galleries

Sample usage (in urls.py):

from feedgenerator import PhotologueFeed

class MyPhotoFeed(PhotologueFeed):
    title = 'My Photologue Galleries'
    description = 'Latest updates to My Photologue Galleries'
    title_template = 'feeds/gallery_feed_title.html'
    description_template = 'feeds/gallery_feed_description.html'    

photofeeds = {
    'gallery': MyPhotoFeed,
}

urlpatterns += patterns('',
    url(r'^photologue/feeds/(?P<url>.*)/$', 'django.contrib.syndication.views.feed', {'feed_dict': photofeeds}),
)

"""
from django.core.urlresolvers import reverse
from django.contrib.syndication.feeds import Feed
from django.contrib.sites.models import Site
from django.utils.feedgenerator import Rss201rev2Feed
from django.utils.http import urlquote

from photologue.models import Gallery

class MediaRSSFeed(Rss201rev2Feed):
    """Basic implementation of Yahoo Media RSS (mrss)
    http://video.search.yahoo.com/mrss

    Includes these elements in the Item feed:
    media:content
        url, width, height
    media:thumbnail
        url, width, height
    media:description
    media:title
    media:keywords
    """
    def rss_attributes(self):
        attrs = super(MediaRSSFeed, self).rss_attributes()
        attrs['xmlns:media'] = 'http://search.yahoo.com/mrss/'
        attrs['xmlns:atom'] = 'http://www.w3.org/2005/Atom'
        return attrs

    def add_item_elements(self, handler, item):
        """Callback to add elements to each item (item/entry) element."""
        super(MediaRSSFeed, self).add_item_elements(handler, item)

        if 'media:title' in item:
            handler.addQuickElement(u"media:title", item['title'])
        if 'media:description' in item:
            handler.addQuickElement(u"media:description", item['description'])

        if 'content_url' in item:
            content = dict(url=item['content_url'])
            if 'content_width' in item:
                content['width'] = str(item['content_width'])
            if 'content_height' in item:
                content['height'] = str(item['content_height'])
            handler.addQuickElement(u"media:content", '', content)
        
        if 'thumbnail_url' in item:
            thumbnail = dict(url=item['thumbnail_url'])
            if 'thumbnail_width' in item:
                thumbnail['width'] = str(item['thumbnail_width'])
            if 'thumbnail_height' in item:
                thumbnail['height'] = str(item['thumbnail_height'])
            handler.addQuickElement(u"media:thumbnail", '', thumbnail)

        if 'keywords' in item:
            handler.addQuickElement(u"media:keywords", item['keywords'])
                                

class PhotologueFeed(Feed):
    """Basic Feed implementation for generating a MediaRSS feed for photologue galleries
    To customize, subclass and override these attributes:
        title
        description
        title_template
        description_template
        item_limit
    """
    feed_type = MediaRSSFeed

    sitename = Site.objects.get_current().name

    title = '%s Gallery' % (sitename,)
    description = '%s Photo Gallery' % (sitename,)
    title_template = 'gallery_feed_title.html'
    description_template = 'gallery_feed_description.html'
    item_limit = 10

    def get_object(self, bits):
        """
        Returns objects based on slug fed through URL
        e.g.
        <url-slug>/gallery-title-slug/
        returns photos in gallery-title-slug
        
        <url-slug>/
        returns latest 10 galleries with sample photos.
            links are to gallery feeds
        """

        if len(bits) == 0:
            return None
        elif len(bits) > 1:
            return ObjectDoesNotExist
        else:
            return Gallery.objects.get(title_slug__exact=bits[0])

    def link(self, gallery):
        """Returns link to either the archive list URL or specific gallery URL"""
        if gallery is None:
            return reverse('pl-gallery-archive')
        else:
            return gallery.get_absolute_url()

    def items(self, gallery):
        """Returns up to 'item_limit' public Gallery items or 'item_limit' public photos in a specified Gallery (default=10)
        """
        if gallery is None:
            return Gallery.objects.filter(is_public=True)[:self.item_limit]
        else:
            return gallery.public()[:self.item_limit]

    def item_pubdate(self, obj):
        return obj.date_added

    def item_extra_kwargs(self, obj):
        """Return a dictionary to the feedgenerator for each item to be added to the feed.
        If the object is a Gallery, uses a random sample image for use as the feed Item
        """
        if isinstance(obj, Gallery):
            photo = obj.sample(1)[0]
            photo.caption = obj.description
        else:
            photo = obj

        item = {'media:title': photo.title,
                'media:description': photo.caption,
                'content_url': photo.get_display_url(),
                'content_width': photo.get_display_size()[0],
                'content_height': photo.get_display_size()[1],
                'thumbnail_url': photo.get_thumbnail_url(),
                'thumbnail_width': photo.get_thumbnail_size()[0],
                'thumbnail_height': photo.get_thumbnail_size()[1],
               }

        if len(photo.tags) > 0:
           keywords = ','.join(photo.tags.split())
           item['keywords'] = keywords

        return item

# Convenience for supplying feed_dict to django.contrib.syndication.views.feed in url
photofeeds = {
    'gallery': PhotologueFeed,
}

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 2 months ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 2 months, 1 week ago
  3. Serializer factory with Django Rest Framework by julio 9 months, 1 week ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 9 months, 4 weeks ago
  5. Help text hyperlinks by sa2812 10 months, 3 weeks ago

Comments

shellsage (on September 4, 2009):

You're missing the import:

from django.core.exceptions import ObjectDoesNotExist

And on line 113 it should be raise, not return.

#

Please login first before commenting.