博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

python实现xauth的客户端

Posted on 2012-08-30 11:15  刘乐  阅读(269)  评论(0)    收藏  举报

1、用到的库 oauth2 urllib hashlib base64 hmac

2、实现的内容,成功获取access_token 实现具体业务请求


access_token获取params字典,顺序放入需要的key和value,申请Consumer(保存key和secret),设置set_signature_method的方法SignatureMethod_HMAC_SHA1,然后请求即可client.request

        x_auth_username = ""

        x_auth_password = ""

        x_auth_model = "client_auth"

        oauth_signature_method = "HMAC-SHA1"

        oauth_timestamp = int(time.time()).__str__()

        oauth_nonce = int(time.time()).__str__()

        oauth_version = "1.0"

        params = {}

        params["oauth_consumer_key"] = self.oauth_consumer_key

        params["oauth_nonce"] = oauth_nonce

        params["oauth_signature_method"] = oauth_signature_method

        params["oauth_timestamp"] = oauth_timestamp

        params["oauth_version"] = oauth_version

        params["x_auth_model"] = x_auth_model

        params["x_auth_password"] = x_auth_password

        params["x_auth_username"] = x_auth_username

        

        consumer = oauth2.Consumer(self.oauth_consumer_key, self.oauth_consumer_secret)

        client = oauth2.Client(consumer)

        client.add_credentials(x_auth_username,x_auth_password)

        client.set_signature_method = oauth2.SignatureMethod_HMAC_SHA1()

        print params

        resp, token = client.request(access_token_url, method="POST", body=urllib.urlencode(params))

        print 'testOauth' + token


3、具体业务实现,跟获取token相似,参数不同,需要通过basestring获取signature

signature = base64.b64encode(hmac.new(self.oauth_consumer_secret+'&',baseString, hashlib.sha1).digest())

其中携带的参数需要做XOR,str做XOR需要先ord,然后异或计算,最后chr

for i in range( params1.__len__()):

            abc = i%self.oauth_consumer_secret.__len__()

            result.append(chr(ord(params1[i]) ^ ord(self.oauth_consumer_secret[abc])))


headers_test['Content-Type'] = "application/x-www-form-urlencoded; charset=UTF-8"

我们的api发现不是很标准,只能跟现有的进行处理,先做UTF-8,然后urlencode。


注:

chr()函数用一个范围在range(256)内的(就是0~255)整数作参数,返回一个对应的字符。 unichr()跟它一样,只不过返回的是Unicode字符,这个从Python 2.0才加入的unichr()的参数范围依赖于你的Python是如何被编译的。如果是配置为USC2的Unicode,那么它的允许范围就是 range(65536)或0x0000-0xFFFF;如果配置为UCS4,那么这个值应该是range(1114112)或 0x000000-0x110000。如果提供的参数不在允许的范围内,则会报一个ValueError的异常。

ord()函数是chr()函数(对于8位的ASCII字符串)或unichr()函数(对于Unicode 对象)的配对函数,它以一个字符(长度为1的字符串)作为参数,返回对应的ASCII数值,或者Unicode数值,如果所给的Unicode字符超出了 你的Python定义范围,则会引发一个TypeError的异常。