- Author:
- baumer1122
- Posted:
- August 24, 2007
- Language:
- Python
- Version:
- .96
- 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
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 6 months ago
Comments
Please login first before commenting.