开发者

Getting users latest tweet with Django

I want to create a function which grabs every users latest tweet from a specific group. So, if a user is in the 'authors' group, I want to grab their latest tweet and then finally cache the result for the day so we only do the cra开发者_运维技巧zy leg work once.

    def latest_tweets(self):
    g = Group.objects.get(name='author')
    users = []
    for u in g.user_set.all():
        acc = u.get_profile().twitter_account
        users.append('http://twitter.com/statuses/user_timeline/'+acc+'.rss')
    return users

Is where I am at so far, but I'm at a complete loose end as to how I parse the RSS to get there latest tweet. Can anyone help me out here? If there is a better way to do this, any suggestions are welcome! I'm sure someone will suggest using django-twitter or other such libraries, but I'd like to do this manually if possible.

Cheers


why redo the stone?, you can download/install/import python-twitter and do something like:

tweet = twitter.Api().GetUserTimeline( u.get_profile().twitter_account )[0]

http://code.google.com/p/python-twitter/

an example: http://www.omh.cc/blog/2008/aug/4/adding-your-twitter-status-django-site/


Rss can be parsed by any xml parser. I've used the built-in module htmllib before for a different task and found it easy to deal with. If all you're doing is rss parsing though, I'd recommend feedparser. I haven't used it before, but it seems pretty straight forward.


If you go with python-twitter it is pretty simple. This is from memory so forgive me if I make a mistake here.

from django.core.cache import cache
import twitter


TWITTER_USER = 'username'
TWITTER_TIMEOUT = 3600

def latest_tweet(request):

  tweet = cache.get('tweet')
  if tweet:
    return {"tweet":tweet}

  api = twitter.Api()
  tweets = api.GetUserTimeline(TWITTER_USER)
  tweet = tweets[0]

  tweet.date = datetime.strptime(
    tweet.created_at, "%a %b %d %H:%M:%S +0000 %Y"
  )

  cache.set( 'tweet', tweet, TWITTER_TIMEOUT )

  return {"tweet": tweet}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜