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

(编辑:jimmy 日期: 2024/11/21 浏览:2)

开发环境:python版本2.X

复制代码 代码如下:
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# 适合python版本:2.X

import sys, urllib, re
import oauth.oauth as oauth
from urllib2 import Request, urlopen

status = 'hello world !' # send message

consumer_key = '...'     # api key
consumer_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"] = username
params["x_auth_password"] = passwd
params["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 got
m = re.match(r'oauth_token=(?P<key>[^&]+)&oauth_token_secret=(?P<secret>[^&]+)', 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()

一句话新闻
高通与谷歌联手!首款骁龙PC优化Chrome浏览器发布
高通和谷歌日前宣布,推出首次面向搭载骁龙的Windows PC的优化版Chrome浏览器。
在对骁龙X Elite参考设计的初步测试中,全新的Chrome浏览器在Speedometer 2.1基准测试中实现了显著的性能提升。
预计在2024年年中之前,搭载骁龙X Elite计算平台的PC将面世。该浏览器的提前问世,有助于骁龙PC问世就获得满血表现。
谷歌高级副总裁Hiroshi Lockheimer表示,此次与高通的合作将有助于确保Chrome用户在当前ARM兼容的PC上获得最佳的浏览体验。