python新浪微博认证及发微

时间:2021-09-14 08:31:51

新浪微博认证需要安装新浪微博的API(Python),安装好后就可以使用微博提供的的各种接口。这里只简单介绍认证和发微。·

首先可以通过微博开放平台注册应用申请APP_KEY和APP_SECRET,它们是认证所必须的。(无需审核已经可以用很多接口了)

新浪微博开放平台:http://open.weibo.com/

例如我的应用:

python新浪微博认证及发微

设置OAuth2认证的回调地址,这里我设置了默认地址:(回调地址用来接收认证成功的准入序列号)

python新浪微博认证及发微

OAuth2认证过程如下图:

python新浪微博认证及发微

以下是login.py登陆认证模块,返回OAuth2认证成功的APIClient对象:

#login module
import urllib
import urllib2
import sys
from weibo import APIClient
import myConfig as con

def login():
client = APIClient(app_key=con.APP_KEY, app_secret=con.APP_SECRET, redirect_uri=con.CALLBACK_URL)
# get authorization url (resource owner)
referer_url = client.get_authorize_url()
# print referer_url
cookies = urllib2.HTTPCookieProcessor()
opener = urllib2.build_opener(cookies)
urllib2.install_opener(opener)

postdata = {
"client_id": con.APP_KEY,
"redirect_uri": con.CALLBACK_URL,
"userId": con.USERID,
"passwd": con.PASSWD,
"isLoginSina": "0",
"action": "submit",
"response_type": "code"
}

headers = {
"User-Agent":"Guess",
"Host":"api.weibo.com",
"Referer":referer_url
}

req = urllib2.Request(
url=referer_url,
data=urllib.urlencode(postdata),
headers=headers
)
try:
# get authorization grant
resp=urllib2.urlopen(req)
# print resp.geturl()

# get request code for access token
code=resp.geturl()[-32:]

# get access token
r=client.request_access_token(code)

client.set_access_token(r.access_token, r.expires_in)
print "login success!"
return client
except Exception, e:
print "login error!"
print e
其中myConfig是我的配置文件:

APP_KEY = 'xxxxxxxxx'
APP_SECRET = 'xxxxxxxxxxxxxxxxxxxxxxxxxxx'
CALL_BACK = 'https://api.weibo.com/oauth2/default.html'
CALLBACK_URL = 'https://api.weibo.com/oauth2/default.html'
USERID = 'username'
PASSWD = 'password'

如果认证成功,那么就可以通过该APIClient对象进行一系列的操作,最基本的如发送微博:

client.statuses.upload.post(status='love is a beauty')