This article mainly introduces python's xauth Method for logging on to fanwe and sending a message example. If you need it, refer to the development environment: python version 2.X.
The Code is as follows:
#! /Usr/bin/env python
#-*-Coding: UTF-8 -*-
# Python version: 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 = 'oss realm = "% s" '% realm
# Add the oauth parameters.
If request. parameters:
For k, v in request. parameters. iteritems ():
If k. startswith ('oss _ ') 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 [^ &] +) & 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 ()