Jon Loyens RSS

Technologist, Tennis Fan, Musician

Archive

Dec
29th
Mon
permalink

Something quick and useful with Django and the Twitter API

Last night a friend contacted me about wanting to put together a quick stats application for Twitter.  I had never messed with the Twitter API before and didn’t know what was possible so I poked around and wrote up a simple application in a couple of hours.

The application I chose to write performs a simple task that’s actually surprisingly hard to do with Twitter’s interface:  Figure out which of your followers is following you back.  Twitter alerts you when someone starts following you but doesn’t when someone stops, so sometimes its hard to know when your @replies are falling on deaf ears.  This app solves that problem (and also lets you know which people to drop if they’re no longer following you too).

Without further ado, here’s the application: Twitter follow-back (please note that if a lot of people start hitting this, it may bump up against the Twitter api rate limit).

Using Django and the python-twitter api this was really easy to write.  The entire application is essentially one form and one view (no models, admin or anything else).  On GET the view renders the form which asks for a twitter username and password.  Here’s the (very simple) code for the form:

from django import forms
class TwitterUserInfoForm(forms.Form):
    ”“” TwitterUserInfoForm
    collect a twitter user name and password
    ”“”
    
    username = forms.CharField(label=”Twitter Username”)
    password = forms.CharField(widget=forms.PasswordInput, label=”Twitter Password”,help_text=”We won’t store this anywhere” )

Next up was the view itself that did the processing.  The python-twitter api is nice and pythonic.  For example,it nicely implements the equivalence operator on the twitter.User class such that a user that shows up in the followers list evaluates as equal to the same user object in the following list.  This allows us to use the ‘in’ operator to detect if the user is in both lists.  Additionally, this python-twitter api makes very thorough use of pythonic exceptions.  Here’s the post code from the view:

def follow_back(request):
    error = None
    if request.POST:
        form = TwitterUserInfoForm(request.POST)

        if form.is_valid():
    try:
        api = twitter.Api(username=form.cleaned_data[‘username’],                      password=form.cleaned_data[‘password’])
        friends = api.GetFriends()
        friends.sort(sort_by_screen_name)
        followers = api.GetFollowers()

        for friend in friends:
             friend.follows_me = friend in followers

        return render_to_response(‘twstats/followback_results.html’,
                  {‘friends’ : friends },
                  context_instance=RequestContext(request))
     except HTTPError, e:
        if e.code == 401:
            error = “Unknown Username/Password”
     else:
        error = str(e)
     except Exception, e:
        error = str(e)

    else:
        form = TwitterUserInfoForm()

    return render_to_response(‘twstats/followback_form.html’,
              {‘form’ : form, ’error’ : error, },
              context_instance=RequestContext(request))

I was going to try and deploy this as a google appengine application and got about 75% of the way there but unfortunately, python-twitter will need a bit more of a re-write since many of it’s dependencies are available in the Google appengine.  Therefore for the time being, it will exist in my webfaction account.

Enjoy.