#!/usr/bin/python # coding=utf-8 import urllib2 import xml.dom.minidom import winsound import time import thread import urllib public_timeline_url = "http://api.fanfou.com/statuses/public_timeline.xml" user_timeline_url = "http://api.fanfou.com/statuses/user_timeline.xml" friends_timeline_url = "http://api.fanfou.com/statuses/friends_timeline.xml" statuses_update_url = "http://api.fanfou.com/statuses/update.xml" # friendship related friendships_create_url = "http://api.fanfou.com/friendships/create.xml" friendships_destroy_url = "http://api.fanfou.com/friendships/destroy.xml" # block list blocks_create_url = "http://api.fanfou.com/blocks/create.xml" blocks_destroy_url = "http://api.fanfou.com/blocks/destroy.xml" passwd_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm() passwd_mgr.add_password(realm=None, uri='http://api.fanfou.com/', user='xxxxxxx', passwd='xxxxxxxxx') # 用户名和密码 auth_handler = urllib2.HTTPBasicAuthHandler(passwd_mgr) opener = urllib2.build_opener(auth_handler) last_id = '' def parseDom(doc): sts = doc.getElementsByTagName('status') get_textValue = lambda tag: \ (lambda d:d.getElementsByTagName(tag)[0].childNodes[0].data) create_time = get_textValue('created_at') id_str = get_textValue('id') text = get_textValue('text') username = get_textValue('name') return [(username(node), text(node), create_time(node), id_str(node)) for node in sts][::-1] def refresh(): global last_id print last_id res = opener.open(friends_timeline_url) doc = xml.dom.minidom.parseString(res.read()) posts = parseDom(doc) id_list = [ids for (_, _, _, ids) in posts] if last_id in id_list: id_list = id_list[id_list.index(last_id)+1:] winsound.MessageBeep(winsound.MB_ICONASTERISK) print for (user, txt, tm, ids) in posts: print "{%s}: %s [%s]" % (user, txt, tm.split()[3]) last_id = posts[-1][-1] print 'MyMsg:', def refresh_thread(times=0, timeout=60): f = False if times== 0: f = True while f or times: refresh() time.sleep(timeout) def post_statue(msg, reply=''): if not msg: return #msg = unicode(msg, 'gbk') data = {'status' : msg, 'in_reply_to_status_id' : reply, 'source' : 'ffsh'} data = urllib.urlencode(data) opener.open(statuses_update_url, data) thread.start_new_thread(refresh_thread, (0,30)) while True: mymsg = raw_input('MyMsg: ') post_statue( mymsg )
andelf fledna Feather
2009年2月24日星期二
HTTP Basic 验证HTTPBasicAuthHandler
以 fanfou api 为例说明.
有兴趣的可以做个功能完整的工具.
订阅:
博文评论 (Atom)
没有评论:
发表评论