前提:在新浪微博应用开发平台成功创建一个应用,并获得可用APP_KEY、APP_SECRET、CALLBACK_URL。
1.下载OAuth2的python版SDK,https://github.com/michaelliao/sinaweibopy,其中封装的新浪微博API的文件是weibo.py;
2.使用SDK开发微博应用程序,直接上源码:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from weibo import *
import urllib,httplib
APP_KEY = '581******';
APP_SECRET = '99870459fe54833***********************';
CALLBACK_URL = 'http://apps.weibo.com/*********';
ACCOUNT = 'tb*******';
PASSWORD = '************';
def get_code(url):
conn = httplib.HTTPSConnection('api.weibo.com');
postdata = urllib.urlencode ({
'client_id':APP_KEY,
'response_type': 'code',
'redirect_uri':CALLBACK_URL,
'action':'submit',
'userId':ACCOUNT,
'passwd':PASSWORD,
'isLoginSina':0,
'from':'',
'regCallback':'',
'state':'',
'ticket':'',
'withOfficalFlag':0
});
conn.request('POST','/oauth2/authorize',postdata,{'Referer':url,'Content-Type': 'application/x-www-form-urlencoded'});
res = conn.getresponse();
#print 'headers===========',res.getheaders();
#print 'msg===========',res.msg;
#print 'status===========',res.status;
#print 'reason===========',res.reason;
#print 'version===========',res.version;
location = res.getheader('location');
code = location.split('=')[1];
conn.close();
return code;
def get_authorize():
client = APIClient(app_key=APP_KEY, app_secret=APP_SECRET, redirect_uri=CALLBACK_URL);
authorize_url = client.get_authorize_url();
code = get_code(authorize_url);
r = client.request_access_token(code);
client.set_access_token(r.access_token, r.expires_in);
return client;
if __name__ == '__main__':
client = get_authorize();
#print client.get.friendships__friends(uid='2100610530');
#print client.get.users__show(uid=2100610530);
#r = client.statuses.user_timeline.get();
r = client.statuses__user_timeline();
print r.total_number;
for st in r.statuses:
print st.user.screen_name;
3.SDK的使用规则:
1)使用微博API,需要通过用户的授权,获取用户的授权码code;
2)该SDK调用API的方法名称映射规则有以下几种,以API中的statuses/public_timeline接口为例:
a)client.get.statuses__public_timeline(),将"/"换为两个"_",注意是两个。同时根据请求是POST还是GET,使用get或者post;
b)client.statuses__public_timeline(),对于GET方式,在调用API时,可以将get省略;
c)client.statuses.public_timeline.get(),将API中的"/"更换为".",同时最后指定是get方式还是post方式。
3)参数问题:如果API中有参数指定,则在方法中提供参数;
4)返回值:新浪返回的结果是JSON,但是SDK将其封装成了JSON对象,直接通过返回结果调用相应的属性即可。例如:
{
"statuses": [
{
"created_at": "Tue May 31 17:46:55 +0800 2011",
"id": 11488058246,
"text": "求关注。",
"source": "新浪微博",
"favorited": false,
"truncated": false,
"in_reply_to_status_id": "",
"in_reply_to_user_id": "",
"in_reply_to_screen_name": "",
"geo": null,
"mid": "5612814510546515491",
"reposts_count": 8,
"comments_count": 9,
"annotations": [],
"user": {
"id": 1404376560,
"screen_name": "zaku",
"name": "zaku",
"province": "11",
"city": "5",
"location": "北京 朝阳区",
"description": "人生五十年,乃如梦如幻;有生斯有死,壮士复何憾。",
"url": "http://blog.sina.com.cn/zaku",
"profile_image_url": "http://tp1.sinaimg.cn/1404376560/50/0/1",
"domain": "zaku",
"gender": "m",
"followers_count": 1204,
"friends_count": 447,
"statuses_count": 2908,
"favourites_count": 0,
"created_at": "Fri Aug 28 00:00:00 +0800 2009",
"following": false,
"allow_all_act_msg": false,
"remark": "",
"geo_enabled": true,
"verified": false,
"allow_all_comment": true,
"avatar_large": "http://tp1.sinaimg.cn/1404376560/180/0/1",
"verified_reason": "",
"follow_me": false,
"online_status": 0,
"bi_followers_count": 215
}
},
...
],
"previous_cursor": 0, // 暂未支持
"next_cursor": 11488013766, // 暂未支持
"total_number": 81655
}
对于该返回的JSON格式,r为SDK的返回结果,则通过r.statuses即可获取JSON中的statuses列表,r.total_number获取JSON中的total_number属性,r.statuses[0].user.id获得statuses列表第一个元素的user对象中的id。