Posting to the Twitter API on an admin change

Posted by: barbara | Date: Apr 07, 2009 | Category: django    

For context, I've been working on a project that involves submitted messages going through a manual review process - once they've been approved in the admin, each message should be posted to Twitter. My Twitter API script is over here, for reference.

I had originally thought I'd set up a cron job to run the posting script, and I still might go back to that if the manual review from the admin starts to take too much time. Doug Hellman suggested using signals, but after some consideration I realized that Django signals would probably be overkill - it's a little disappointing because I've never actually gotten signals working in a project. I need a use case to make me figure it out, and I thought this would be it.

Instead I was browsing some old code and realized that, oh yeah, I can put a save method in my admin class ... honestly, I'm embarrassed that I didn't think of it first - it's a no-brainer.

I just wrapped all the script code in a method:

    #!/usr/bin/python
    
    import MySQLdb as Database
    import base64, urllib, urllib2
    
    def main():
        db = Database.connect("myhost", "myuser", "mypasswd", "mydbname")
        cursor = db.cursor(Database.cursors.DictCursor)
    
        sql = """SELECT * FROM twitter_message WHERE approved=1 AND posted=0"""
        cursor.execute(sql)
        data = cursor.fetchall()
    
        username = "twitter_username"
        password = "twitter_password"
    
        for record in data:
            message = record["message"]
            message = message.replace(',', '')
            post_data = {'status': message}
    
            request = urllib2.Request('http://twitter.com/statuses/update.json')
            request.headers['Authorization'] = 'Basic %s' % ( base64.b64encode(username + ':' + password),)
            request.data = urllib.urlencode({'status': message})
            response = urllib2.urlopen(request) # The Response
    
            """ the most painful part is hacking up the response to get at the status id """
            a = response.read()
            b = a.split(',') ## convert the whole thing to a list
            c = b[30] ## hope the id is always the 30th item in the list
            d = INT(c[5:]) ## strip off first part of string, leave behind the number
          
            if response.code == 200 and type(d) == int:
                record_id = record["id"]
                sql = """UPDATE twitter_message posted=1, post_date=NOW(), status_id=%s WHERE id=%s""" %(d, record_id)
                cursor.execute(sql)
    
        cursor.close()
        db.close()
    
    if __name__ == "__main__":
        main()
    

Then imported it as a module and called it from the relevant admin.py:

    import twitterpost
    
    class TweetAdmin(admin.ModelAdmin):
        def save_model(self, request, obj, form, change):
            obj.save()
            if obj.approved: twitterpost.main()
        list_filter = ('approved',)
    

Note that the script is called after the obj.save() - the script only acts on records that have already been marked 'approved'.

That's it. Three extra lines of code (six if you count what I added to the script).

Comment by Ronny on Apr 07, 2009:
I've used python-twitter (http://code.google.com/p/python-twitter/) in one of my Django projects and I'm very happy with it.
This is incredibly helpful! We recently had someone speak up about a need for something like this, and this should do the trick! If we do end up using it, I'll let you know. Then you can put NASA on your resume!
Comment by lifewithryan on Apr 07, 2009:
I was trying to tweet this from my blackberry the other day when I read your post, but it wasn't working, so I gave up and never got to reply back -- but overriding the save method was going to be my suggestion...*honest*
Comment by Ash Christopher on Apr 07, 2009:
I used Python Twitter Tools (http://mike.verdone.ca/twitter/) for twitter integration. It is simple to use, forward compatible (so long as Twitter continues to use REST) and it has all sorts of other goodies in addition to the library. IRC bot, console client, etc.
Comment by Barbara on Apr 07, 2009:
For everyone suggesting python-twitter: I agree that it's a great set of tools, but I mentioned in my earlier post that I decided to write my own because I don't need that much functionality - for my own project, I'm only doing posts, so I didn't want all the code overhead.
Comment by mksoft on Apr 17, 2009:
Since you already have the object from save_model, it seems inefficient to you execute another connection/query do the db (and coupling it with mysql) instead of passing obj to the function (plus main is not a very good name - a descriptive one would be better).
Comment by teemPoili4 on Mar 08, 2011:
This actually answered my downside, thank you!
Comment by parthiban M on May 04, 2011:
I had originally anticipation I'd set up a cron job to run the announcement script, and I still ability go aback to that if the chiral analysis from the admin starts to yield too abundant time.
Comment by combustíveis on May 08, 2011:
Barbara: this is genius! Like you said, why couldn't we have thought of this first? :) Anyways, it's been working great for me and have been very helpful. Thanks for sharing; I know my fellow webmaster friends will be excited!
Comment by Peter Fry on May 23, 2011:
I have implemented the code on two of my sites and it looks great. Many thanks
Comment by Shaadi on May 26, 2011:
Such an good an informative idea and Code thanks for the help
Comment by Lyrics on May 26, 2011:
API working good and having a good effect in twitter admin panel . thanks
Comment by gadgetyoki on May 28, 2011:
wow,,,,, i like this code! thanks for the tutorial! :D
Comment by George Lagroon on Jun 02, 2011:
Your post is quite interesting and useful. I have bookmarked this site for later use to see what other great articles you post!
Comment by samy on Jun 02, 2011:
great script it's really help me...
Comment by mensajes claro on Jun 05, 2011:
The codes you provided above is really a great help for our project... thanks!
Comment by Some Guy on Jun 12, 2011:
Great site but you should moderate the comments :)
Comment by Levitra on Jun 13, 2011:
nice post about twitter
This really answered my problem, thank you!
Comment by fredmoligess on Jun 17, 2011:
We recently had someone speak up about a need for something like this, and this should do the trick! If we do end up using it, I'll let you know. Then you can put NASA on your resume!