Login

Feed Reader Inclusion Tag with Caching

Author:
baumer1122
Posted:
August 24, 2007
Language:
Python
Version:
.96
Tags:
feed rss inclusion-tag
Score:
3 (after 3 ratings)

A revisit of the original snippet with simple caching.

 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
import urllib, os, time, datetime, feedparser
CACHE_FOLDER = '/path/to/cache/'

@register.inclusion_tag('my_template.html')
def pull_feed(feed_url, posts_to_show=5, cache_expires=30):
    CACHE_FILE = ''.join([CACHE_FOLDER, template.defaultfilters.slugify(feed_url), '.cache'])
    try:
        cache_age = os.stat(CACHE_FILE)[8]
    except: #if file doesn't exist, make sure it gets created
        cache_age = 0
    #is cache expired? default 30 minutes (30*60)
    if (cache_age + cache_expires*60 < time.time()):
        try: #refresh cache
            urllib.urlretrieve(feed_url,CACHE_FILE)
        except IOError: #if downloading fails, proceed using cached file
            pass
    #load feed from cache
    feed = feedparser.parse(open(CACHE_FILE))
    posts = []
    for i in range(posts_to_show):
        pub_date = feed['entries'][i].updated_parsed
        published = datetime.date(pub_date[0], pub_date[1], pub_date[2] )
        posts.append({
            'title': feed['entries'][i].title,
            'summary': feed['entries'][i].summary,
            'link': feed['entries'][i].link,
            'date': published,
        })
    return {'posts': posts}

More like this

  1. Feed Reader Inclusion Tag by baumer1122 7 years, 11 months ago
  2. Parsed RSS into template var by bram 7 years ago
  3. Filter by first letter inclusion tag by slafs 5 years, 1 month ago
  4. Syndication Feed for JSON by cato 2 years, 7 months ago
  5. Cache Backend using memcached including prefix settings by mojemeno123 3 years ago

Comments

Please login first before commenting.