7 0
A
ABOUT
15
7 0
DABEAZ LLC
T
TEACHING
7 0
C
CONSULTING
7 0
S
SOFTWARE
7 0
B
BLOG
7 0
- - - E C P T O
STATUS REGISTER
E:Python Essential Reference, 4th Edition
C:Python Cookbook, 3rd Edition
P:Chicago-area Python Classes
T:Talks & Tutorials
O:Office

 # -----------------------------------------------------------------------------
 # twithandler.py
 #
 # Copyright (C) 2009
 # David Beazley (http://www.dabeaz.com)
 #
 # A Twitter handler for use with the logging module.
 # ----------------------------------------------------------------------
 
 from logging import Handler
 import urllib2, urllib
 
 class TwitHandler(Handler):
     def __init__(self,username,password):
         Handler.__init__(self)
         auth = urllib2.HTTPBasicAuthHandler()
         auth.add_password("Twitter API","http://twitter.com",username,password)
         self.__opener = urllib2.build_opener(auth)
     def emit(self,record):
         try:
             msg = self.format(record)
             fields = {
                 'status' : msg.encode('ascii','replace')[:140]
                 }
             parms = urllib.urlencode(fields)
             request = urllib2.Request("http://twitter.com/statuses/update.json",parms)
             u = self.__opener.open(request)
             resp = u.read()
         except (KeyboardInterrupt,SystemExit):
             raise
         except:
             self.handleError(record)