新浪微博开放接口调用微博API怎么样?(图)

优采云 发布时间: 2021-06-01 01:29

  新浪微博开放接口调用微博API怎么样?(图)

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

  SDK下载链接:代码不超过十几K,完全可以理解。

  如果你有微博账号,你可以创建一个新的应用,然后你就可以得到应用密钥和应用秘钥,这是应用获得OAuth2.0授权所必需的。

  要了解OAuth2,可以查看新浪微博链接的说明。除了app key和app secret外,OAuth2授权参数还需要网站回调地址redirect_uri,而且这个回调地址不允许在局域网内(不管localhost,127.0.0. ]1 好像不行),这个真的让我着急了好久。我没有使用API​​调用网站,所以查了很多。看到有人写道可以改用该地址,我尝试了一下,这样就可以了,这对Diosi来说是个好消息。

  我们先来一个简单的程序来感受一下:

  设置以下参数

  import sys

import weibo

import webbrowser

APP_KEY = ''

MY_APP_SECRET = ''

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

  获取微博授权网址,如第二行,用默认浏览器打开后,会要求登录微博,用需要授权的账号登录,如下图

  1 api = weibo.APIClient(app_key=APP_KEY,app_secret=MY_APP_SECRET,redirect_uri=REDIRECT_URL)

2 authorize_url = api.get_authorize_url()

3 print(authorize_url)

4 webbrowser.open_new(authorize_url)

  

  登录后会转成一个连接代码=92cc6accecfb5b2176adf58f4c

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

  1 request = api.request_access_token(code, REDIRECT_URL)

2 access_token = request.access_token

3 expires_in = request.expires_in

4 api.set_access_token(access_token, expires_in)

5 api.statuses.update.post(status=u'Test OAuth 2.0 Send a Weibo!')

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

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

  

  但是,这样的手动代码输入方式并不适合调用程序。是否可以在不打开链接的情况下请求登录并获得授权?经过多方搜索参考,对程序进行如下改进,可以自动获取并保存代码,方便程序服务调用。

  

  

  访问微博

  # -*- 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!')

  

  

  重试.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 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

  

  

0 个评论

要回复文章请先登录注册


官方客服QQ群

微信人工客服

QQ人工客服


线