python使用xauth方式登录饭否网然后发消息

开发环境:python版本2.x

代码如下:

#!/usr/bin/env python# -*- coding:utf-8 -*-# 适合python版本:2.x

import sys, urllib, reimport oauth.oauth as oauthfrom urllib2 import request, urlopen

status = ‘hello world !’ # send message

consumer_key = ‘…’ # api keyconsumer_secret = ‘…’ # api secret

access_token_url = ‘http://fanfou.com/oauth/access_token’verify_url = ‘http://api.fanfou.com/account/verify_credentials.xml’post_url = ‘http://api.fanfou.com/statuses/update.xml’

def request_to_header(request, realm=”): “””serialize as a header for an httpauth request.””” auth_header = ‘oauth realm=”%s”‘ % realm # add the oauth parameters. if request.parameters: for k, v in request.parameters.iteritems(): if k.startswith(‘oauth_’) or k.startswith(‘x_auth_’): auth_header += ‘, %s=”%s”‘ % (k, oauth.escape(str(v))) return {‘authorization’: auth_header}

# get username and password from command line username = sys.argv[1]passwd = sys.argv[2]

consumer = oauth.oauthconsumer(consumer_key, consumer_secret)params = {}params[“x_auth_username”] = usernameparams[“x_auth_password”] = passwdparams[“x_auth_mode”] = ‘client_auth’request = oauth.oauthrequest.from_consumer_and_token(consumer, http_url=access_token_url, parameters=params)signature_method = oauth.oauthsignaturemethod_hmac_sha1()request.sign_request(signature_method, consumer, none)headers=request_to_header(request)

resp = urlopen(request(access_token_url, headers=headers))token = resp.read()print token # access_token gotm = re.match(r’oauth_token=(?p[^&]+)&oauth_token_secret=(?p[^&]+)’, token)if m: oauth_token = oauth.oauthtoken(m.group(‘key’), m.group(‘secret’)) params[‘status’]=status request = oauth.oauthrequest.from_consumer_and_token(consumer, http_method=’post’, token=oauth_token, http_url=post_url, parameters=params) request.sign_request(signature_method, consumer, oauth_token) headers=request_to_header(request) resp = urlopen(request(url=post_url, data=urllib.urlencode({‘status’:status}), headers=headers)) print resp.read()

Posted in 未分类

发表评论