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的判断语句模拟三目运算
Apr 24 Python
Python使用matplotlib绘制动画的方法
May 20 Python
python selenium 获取标签的属性值、内容、状态方法
Jun 22 Python
Python中pandas dataframe删除一行或一列:drop函数详解
Jul 03 Python
pytorch 数据集图片显示方法
Jul 26 Python
Python打包模块wheel的使用方法与将python包发布到PyPI的方法详解
Feb 12 Python
Python API len函数操作过程解析
Mar 05 Python
浅谈Django QuerySet对象(模型.objects)的常用方法
Mar 28 Python
keras分类模型中的输入数据与标签的维度实例
Jul 03 Python
python 动态绘制爱心的示例
Sep 27 Python
python3实现语音转文字(语音识别)和文字转语音(语音合成)
Oct 14 Python
浅谈pytorch中stack和cat的及to_tensor的坑
May 20 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
新52大事件
2020/03/03 欧美动漫
关于初学PHP时的知识积累总结
2013/06/07 PHP
PHP 冒泡排序 二分查找 顺序查找 二维数组排序算法函数的详解
2013/06/25 PHP
浅析PHP中的字符串编码转换(自动识别原编码)
2013/07/02 PHP
PHP中的排序函数sort、asort、rsort、krsort、ksort区别分析
2014/08/18 PHP
Javascript 验证上传图片大小[客户端]
2009/08/01 Javascript
Jquery提交表单 Form.js官方插件介绍
2012/03/01 Javascript
chrome下img加载对height()的影响示例探讨
2014/05/26 Javascript
14个有用的Jquery技巧分享
2015/01/08 Javascript
js中flexible.js实现淘宝弹性布局方案
2020/06/23 Javascript
JS中mouseover和mouseout多次触发问题如何解决
2016/06/06 Javascript
JS+HTML5 FileReader对象用法示例
2017/04/07 Javascript
详解使用create-react-app快速构建React开发环境
2018/05/16 Javascript
JavaScript简单编程实例学习
2020/02/14 Javascript
javascript实现简易数码时钟
2020/03/30 Javascript
JS替换字符串中指定位置的字符(多种方法)
2020/05/28 Javascript
JS异步宏队列微队列原理详解
2020/09/09 Javascript
详解Python中映射类型的内建函数和工厂函数
2015/08/19 Python
Python常见内置高效率函数用法示例
2018/07/31 Python
不管你的Python报什么错,用这个模块就能正常运行
2018/09/14 Python
Python3爬虫学习之将爬取的信息保存到本地的方法详解
2018/12/12 Python
Python使用import导入本地脚本及导入模块的技巧总结
2019/08/07 Python
python实现logistic分类算法代码
2020/02/28 Python
python之语音识别speech模块
2020/09/09 Python
python 批量将中文名转换为拼音
2021/02/07 Python
任意存:BOXFUL
2018/05/21 全球购物
名词解释WEB SERVICE,SOAP,UDDI,WSDL,JAXP,JAXM;JSWDL开发包的介绍。
2012/10/27 面试题
什么是URL
2015/12/13 面试题
美发店5.1活动方案
2014/01/24 职场文书
优秀团队申报材料
2014/12/26 职场文书
少先队大队委竞选口号
2015/12/25 职场文书
某学校的2019年度工作报告范本
2019/10/11 职场文书
Nginx代理同域名前后端分离项目的完整步骤
2021/03/31 Servers
Python 如何安装Selenium
2021/05/06 Python
Redis源码阅读:Redis字符串SDS详解
2021/07/15 Redis
MySql子查询IN的执行和优化的实现
2021/08/02 MySQL