Skip to content

Instantly share code, notes, and snippets.

@jokull
Created February 11, 2011 13:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jokull/822319 to your computer and use it in GitHub Desktop.
Save jokull/822319 to your computer and use it in GitHub Desktop.
Fetch and cache Facebook status from feed
import datetime
import feedparser
import bleach
from flask import g, Markup
from kex.app import app
class Status(object):
ALLOWED_TAGS = []
def __init__(self, date, content):
self.date = date or datetime.datetime.now()
self.content = content or ''
def to_dict(self):
return {'date': self.date, 'content': self.content}
def clean(self):
print self.date
return dict(
date=datetime.datetime(*feedparser._parse_date(self.date)[:6]),
content=Markup(bleach.clean(self.content, tags=self.ALLOWED_TAGS, strip=True))
)
class FacebookFeed(object):
KEY = '%s-fb-status-'
FEED_URL = 'http://www.facebook.com/feeds/page.php?format=atom10&id=%s'
EXPIRE = 60 * 15
def __init__(self):
self.feed_url = self.FEED_URL % app.config['FB_PAGE_ID']
self.key = self.KEY % app.config['FB_PAGE_ID']
def update(self):
try:
feed = feedparser.parse(self.feed_url)
post = feed['items'][0]
status = Status(post['updated'], post['content'][0]['value'])
g.redis.hmset(self.key, status.to_dict())
g.redis.expire(self.key, self.EXPIRE)
except IndexError:
status = Status()
return status
@property
def status(self):
_status = g.redis.hmget(self.key, ('date', 'content'))
if not all(_status):
status = self.update()
else:
status = Status(*_status)
return status.clean()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment