![]() |
version seven.   http://demongin.org |
Django and #twyt
A short "how to" that describes using "TWYT" to automatically tweet about new blog posts.
Tuesday, 2009-08-04 | demongin.org, Django, On the Internet, Programming
| Like a racist, I believed that a strong man could regard the faiths of others as an opportunity for harmless daydreaming and no more. |
| Umberto Eco, Il pendolo di Foucault |
Automatically tweeting when you publish a new blog post on your django blog is pretty much drop-dead simple.
The hardest part (which really is trivial) is overwriting the .save() function for your blog post class and, though that might sound daunting, it's about as easy as falling down the stairs.
But first things first. We're going to be using Andrew Price's twyt module (#twyt, @andyprice), so job number one will be to make sure you've got that mean mamajama installed:
# aptitude update && aptitude install python-twyt
# yum install python-twyt.noarch
If your blog is like mine, you've got a class called "Post" that is your class for all updates to your blog--i.e. the thing that you want to automatically tweet. Here's a quick glance at the important part of my "Post" class from the demongin.org "models.py":
class Post(models.Model): # Fields title = models.CharField(max_length=666) subtitle = models.CharField(max_length=666) quote = models.TextField(blank=True) quote_attribution = models.CharField(max_length=200, blank=True) body = models.TextField() tag = models.ManyToManyField(Tag) pom = models.CharField(max_length=255, default=get_pom) pub_date = models.DateTimeField('date published', default=datetime.datetime.today()) mod_date = models.DateTimeField('date modified', default=datetime.datetime.today())
Overwriting this function, though that sounds complicated, is actually very easy, due the very minimal set of responsibilities that the function has. Once I figured out my twyt syntax, here's how my overwritten .save() function looked:
from twyt import twitter class Post(models.Model): def save(self): """ Overwrite the .save() function to automatically tweet new posts. """ if not self.id: self.pub_date = datetime.date.today() self.mod_date = datetime.datetime.today() twitter_user = "toconnell@tyrannybelle.com" twitter_pass = "XXXXXXXXXX" tweet_string = "'%s' on http://demongin.org" % self.title t = twitter.Twitter() t.set_auth(twitter_user, twitter_pass) t.status_update(tweet_string) super(Post, self).save()
Granted, you're going to need something more sophisticated than this--duplication prevention would be nice, for starters, and passing along a notification message to django so that it could pop up in the admin interface couldn't hurt--in your production code, but this is the guts.
