Skip to content

Instantly share code, notes, and snippets.

@dangayle
Created August 8, 2013 00:47
Show Gist options
  • Save dangayle/6180443 to your computer and use it in GitHub Desktop.
Save dangayle/6180443 to your computer and use it in GitHub Desktop.
import sys
from django.conf import settings
from django.core.cache import cache
from twython import Twython, TwythonError
from ttp.ttp import Parser
from pprint import pprint
def parse_tweet(x):
"""
Parses individual tweets from a user_timeline
"""
parser = Parser()
# if retweet, grab the original poster's info
try:
x = x['retweeted_status']
except:
pass
return {
'profile_image_url': x['user']['profile_image_url'],
'text': parser.parse(x['text']).html
}
def latest_tweets(request):
"""
Gets latest tweet from the Twitter user specified in settings.
Caches latest tweet for 10 minutes to reduce API calls
"""
tweets = cache.get('tweets')
if not tweets:
twitter = Twython(settings.TWITTER_CONSUMER_KEY,
settings.TWITTER_CONSUMER_SECRET,
settings.TWITTER_OAUTH_TOKEN,
settings.TWITTER_OAUTH_TOKEN_SECRET)
try:
user_timeline = twitter.get_user_timeline(
screen_name=settings.TWITTER_USER,
count=10,
exclude_replies=True,
include_rts=False
)
except TwythonError as e:
return {"tweets": e}
tweets = {
'handle': settings.TWITTER_USER,
"tweet": map(parse_tweet, user_timeline)[:5]
}
cache.set('tweets', tweets, settings.TWITTER_CACHE_TIMEOUT)
return {'tweets': tweets}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment