Pew pew pew! (lasers)

May 31, 2009

I’ve been working on a Python project lately with a friend.  The project is a notification system that relies on a pluggable interface for a fair amount of abstraction.  We recently decided that going hog wild with Python modules to run the thing probably wasn’t the best route.  After all, we’re using PyGTK to run the UI and Pysqlite2 for a database.

In an attempt to cleanup dependencies I recently removed an external module from the Gmail checking plugin which allowed very simple authentication on Google’s server and returned a simple response that could be parsed with little to no effort.  The task wasn’t all too difficult to pull off; essentially you need to authenticate of HTTPS and then process the XML response that Google sends back.  Here’s the gist of it:

import urllib2, base64

def make_request( uid, password ):
    request = urllib2.Request( "https://gmail.google.com/gmail/feed/atom" )
    base64string = base64.encodestring( '%s:%s' % ( uid, password ) )[:-1]
    request.add_header( "Authorization", "Basic %s" % base64string )
    response = urllib2.urlopen( request )
    data_set = XMLParser.parseStream( response.read( ) )

    response.close( )

    return int( data_set['fullcount'] )

It’s pretty simple overall: setup your request URI with urllib2.Request(), base64 encode a string in the format of uid:password, set the request header, then just make the request. The return result is irrelevant here, it’s just the total count of new messages.

The resulting response will be an XML document.  The reference to XMLParser is a module I wrote that converts an XML stream into a Python dictionary, but that’s for another day.

This project is being hosted at GitHub: http://github.com/scottferg/Pew-Pew-Notifier/