欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-10-15 15:31:26
因为最近接触到调用新浪微博开放接口的项目,所以就想试试用python调用微博api。 sdk下载地址:http://open.weibo.com/wiki/sdk 代码不...

因为最近接触到调用新浪微博开放接口的项目,所以就想试试用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,我试了一下果然可以,对于屌丝来说是个好消息。

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

设置好以下参数

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