python调用新浪微博API项目实践


Posted in Python onJuly 28, 2014

因为最近接触到调用新浪微博开放接口的项目,所以就想试试用python调用微博API。

SDK下载地址:http://open.weibo.com/wiki/SDK 代码不多十几K,完全可以看懂。

有微博账号可以新建一个APP,然后就可以得到app key和app secret,这个是APP获得OAuth2.0授权所必须的。

了解OAuth2可以查看链接新浪微博的说明。 OAuth2授权参数除了需要app key和app secret还需要网站回调地址redirect_uri,并且这个回调地址不允许是局域网的(神马localhost,127.0.0.1好像都不行),这个着实让我着急了半天。我使用API也不是网站调用,于是查了很多。看到有人写可以用这个地址替代,https://api.weibo.com/oauth2/default.html,我试了一下果然可以,对于?潘坷此凳歉龊孟?ⅰ?/p>

下面先来个简单的程序,感受一下:

设置好以下参数

import sys
import weibo
import webbrowser

APP_KEY = ''
MY_APP_SECRET = ''
REDIRECT_URL = 'https://api.weibo.com/oauth2/default.html'

获得微博授权URL,如第2行,用默认浏览器打开后会要求登陆微博,用需要授权的账号登陆,如下图

api = weibo.APIClient(app_key=APP_KEY,app_secret=MY_APP_SECRET,redirect_uri=REDIRECT_URL)
authorize_url = api.get_authorize_url()
print(authorize_url)
webbrowser.open_new(authorize_url)

python调用新浪微博API项目实践

登陆后会调转到一个连接https://api.weibo.com/oauth2/default.html?code=92cc6accecfb5b2176adf58f4c

关键就是code值,这个是认证的关键。手动输入code值模拟认证

request = api.request_access_token(code, REDIRECT_URL)
access_token = request.access_token
expires_in = request.expires_in
api.set_access_token(access_token, expires_in)
api.statuses.update.post(status=u'Test OAuth 2.0 Send a Weibo!')

access_token就是获得的token,expires_in是授权的过期时间 (UNIX时间)

用set_access_token保存授权。往下就可以调用微博接口了。测试发了一条微博

python调用新浪微博API项目实践

但是这样的手动输入code方式,不适合程序的调用,是否可以不用打开链接的方式来请求登陆获取授权,经多方查找和参考,将程序改进如下,可以实现自动获取code并保存,方便程序服务调用。

accessWeibo

# -*- coding: utf-8 -*- 
#/usr/bin/env python 

#access to SinaWeibo By sinaweibopy 
#实现微博自动登录,token自动生成,保存及更新 
#适合于后端服务调用 


from weibo import APIClient 
import pymongo 
import sys, os, urllib, urllib2 
from http_helper import * 
from retry import * 
try: 
import json 
except ImportError: 
import simplejson as json 

# setting sys encoding to utf-8 
default_encoding = 'utf-8' 
if sys.getdefaultencoding() != default_encoding: 
reload(sys) 
sys.setdefaultencoding(default_encoding) 

# weibo api访问配置 
APP_KEY = '' # app key 
APP_SECRET = '' # app secret 
REDIRECT_URL = 'https://api.weibo.com/oauth2/default.html' # callback url 授权回调页,与OAuth2.0 授权设置的一致 
USERID = '' # 登陆的微博用户名,必须是OAuth2.0 设置的测试账号 
USERPASSWD = '' # 用户密码 


client = APIClient(app_key=APP_KEY, app_secret=APP_SECRET, redirect_uri=REDIRECT_URL) 

def make_access_token(): 
#请求access token 
params = urllib.urlencode({
'action':'submit',
'withOfficalFlag':'0',
'ticket':'',
'isLoginSina':'', 
'response_type':'code',
'regCallback':'',
'redirect_uri':REDIRECT_URL,
'client_id':APP_KEY,
'state':'',
'from':'',
'userId':USERID,
'passwd':USERPASSWD,
}) 

login_url = 'https://api.weibo.com/oauth2/authorize' 

url = client.get_authorize_url() 
content = urllib2.urlopen(url) 
if content: 
headers = { 'Referer' : url } 
request = urllib2.Request(login_url, params, headers) 
opener = get_opener(False) 
urllib2.install_opener(opener) 
try: 
f = opener.open(request) 
return_redirect_uri = f.url 
except urllib2.HTTPError, e: 
return_redirect_uri = e.geturl() 
# 取到返回的code 
code = return_redirect_uri.split('=')[1] 
#得到token 
token = client.request_access_token(code,REDIRECT_URL) 
save_access_token(token) 

def save_access_token(token): 
#将access token保存到MongoDB数据库
mongoCon=pymongo.Connection(host="127.0.0.1",port=27017)
db= mongoCon.weibo

t={
"access_token":token['access_token'],
"expires_in":str(token['expires_in']),
"date":time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
}
db.token.insert(t,safe=True) 

#Decorator 目的是当调用make_access_token()后再执行一次apply_access_token()
@retry(1) 
def apply_access_token(): 
#从MongoDB读取及设置access token 
try: 

mongoCon=pymongo.Connection(host="127.0.0.1",port=27017)
db= mongoCon.weibo
if db.token.count()>0:
tokenInfos=db.token.find().sort([("_id",pymongo.DESCENDING)]).limit(1)
else: 
make_access_token() 
return False 

for tokenInfo in tokenInfos:
access_token=tokenInfo["access_token"]
expires_in=tokenInfo["expires_in"]

try: 
client.set_access_token(access_token, expires_in) 
except StandardError, e: 
if hasattr(e, 'error'): 
if e.error == 'expired_token': 
# token过期重新生成 
make_access_token()
return False 
else: 
pass 
except: 
make_access_token()
return False 

return True 

if __name__ == "__main__": 
apply_access_token() 

# 以下为访问微博api的应用逻辑 
# 以发布文字微博接口为例
client.statuses.update.post(status='Test OAuth 2.0 Send a Weibo!')
retry.py

import math
import time

# Retry decorator with exponential backoff
def retry(tries, delay=1, backoff=2):
"""Retries a function or method until it returns True.

delay sets the initial delay, and backoff sets how much the delay should
lengthen after each failure. backoff must be greater than 1, or else it
isn't really a backoff. tries must be at least 0, and delay greater than
0."""

if backoff <= 1:
raise ValueError("backoff must be greater than 1")

tries = math.floor(tries)
if tries < 0:
raise ValueError("tries must be 0 or greater")

if delay <= 0:
raise ValueError("delay must be greater than 0")

def deco_retry(f):
def f_retry(*args, **kwargs):
mtries, mdelay = tries, delay # make mutable

rv = f(*args, **kwargs) # first attempt
while mtries > 0:
if rv == True or type(rv) == str: # Done on success ..
return rv

mtries -= 1 # consume an attempt
time.sleep(mdelay) # wait...
mdelay *= backoff # make future wait longer

rv = f(*args, **kwargs) # Try again

return False # Ran out of tries :-(

return f_retry # true decorator -> decorated function
return deco_retry # @retry(arg[, ...]) -> true decorator
http_helper.py

# -*- coding: utf-8 -*-
#/usr/bin/env python

import urllib2,cookielib

class SmartRedirectHandler(urllib2.HTTPRedirectHandler):
def http_error_301(cls, req, fp, code, msg, headers):
result = urllib2.HTTPRedirectHandler.http_error_301(cls, req, fp, code, msg, headers)
result.status = code
print headers
return result

def http_error_302(cls, req, fp, code, msg, headers):
result = urllib2.HTTPRedirectHandler.http_error_302(cls, req, fp, code, msg, headers)
result.status = code
print headers
return result

def get_cookie():
cookies = cookielib.CookieJar()
return urllib2.HTTPCookieProcessor(cookies)

def get_opener(proxy=False):
rv=urllib2.build_opener(get_cookie(), SmartRedirectHandler())
rv.addheaders = [('User-agent', 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)')]
return rv
Python 相关文章推荐
python实现的udp协议Server和Client代码实例
Jun 04 Python
Python selenium 父子、兄弟、相邻节点定位方式详解
Sep 15 Python
Python实现中一次读取多个值的方法
Apr 22 Python
使用Py2Exe for Python3创建自己的exe程序示例
Oct 31 Python
PyTorch的Optimizer训练工具的实现
Aug 18 Python
Python使用tkinter模块实现推箱子游戏
Oct 08 Python
python加载自定义词典实例
Dec 06 Python
python数据预处理方式 :数据降维
Feb 24 Python
Python request使用方法及问题总结
Apr 26 Python
python神经网络编程实现手写数字识别
May 27 Python
python 爬取天气网卫星图片
Jun 07 Python
python的html标准库
Apr 29 Python
python中的sort方法使用详解
Jul 25 #Python
python实现监控linux性能及进程消耗性能的方法
Jul 25 #Python
python的dict,set,list,tuple应用详解
Jul 24 #Python
Python常见数据结构详解
Jul 24 #Python
python海龟绘图实例教程
Jul 24 #Python
python实现绘制树枝简单示例
Jul 24 #Python
python实现进程间通信简单实例
Jul 23 #Python
You might like
php中将html中的br换行符转换为文本输入中的换行符
2013/03/26 PHP
php中字符串和正则表达式详解
2014/10/23 PHP
laravel实现登录时监听事件,添加登录用户的记录方法
2019/09/30 PHP
基于PHP实现用户在线状态检测
2020/11/10 PHP
jQuery 选择器、DOM操作、事件、动画
2010/11/25 Javascript
关于eval 与new Function 到底该选哪个?
2013/04/17 Javascript
Query中click(),bind(),live(),delegate()的区别
2013/11/19 Javascript
jQuery判断元素上是否绑定了指定事件的方法
2015/03/17 Javascript
JavaScript 限制文本框不可输入英文单双引号的方法
2016/12/20 Javascript
JavaScript 用fetch 实现异步下载文件功能
2017/07/21 Javascript
解决axios发送post请求返回400状态码的问题
2018/08/11 Javascript
javascriptvoid(0)含义以及与&quot;#&quot;的区别讲解
2019/01/19 Javascript
JavaScript 俄罗斯方块游戏实现方法与代码解释
2020/04/08 Javascript
浅谈React中组件逻辑复用的那些事儿
2020/05/21 Javascript
从零学python系列之数据处理编程实例(一)
2014/05/22 Python
python实现向ppt文件里插入新幻灯片页面的方法
2015/04/28 Python
详解Python 函数如何重载?
2019/04/23 Python
Python基本类型的连接组合和互相转换方式(13种)
2019/12/16 Python
tensorflow模型文件(ckpt)转pb文件的方法(不知道输出节点名)
2020/04/22 Python
HTML5之SVG 2D入门6—视窗坐标系与用户坐标系及变换概述
2013/01/30 HTML / CSS
Java中实现多态的机制是什么?
2014/12/07 面试题
.NET方向面试题
2014/11/20 面试题
工程业务员岗位职责
2013/12/31 职场文书
21岁生日感言
2014/02/27 职场文书
十佳家长事迹材料
2014/08/26 职场文书
运动会加油稿100字
2014/09/19 职场文书
毕业生就业推荐表导师评语
2014/12/31 职场文书
端午节活动总结报告
2015/02/11 职场文书
2015年12.4全国法制宣传日活动总结
2015/03/24 职场文书
工程款申请报告
2015/05/15 职场文书
2016护理专业求职自荐书
2016/01/28 职场文书
2016年第十九届推普周活动总结
2016/04/06 职场文书
python 如何在 Matplotlib 中绘制垂直线
2021/04/02 Python
Nginx使用X-Accel-Redirect实现静态文件下载的统计、鉴权、防盗链、限速等
2021/04/04 Servers
基于Python实现一个春节倒计时脚本
2022/01/22 Python
为自由献出你的心脏!「进击的巨人展 FINAL」2022年6月在台开展
2022/04/13 日漫