使用新浪微博开放平台api同步微博内容至自己网站(试试用python调用微博API的SDK授权所必须的 )

优采云 发布时间: 2021-12-10 10:13

  使用新浪微博开放平台api同步微博内容至自己网站(试试用python调用微博API的SDK授权所必须的

)

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

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

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

  要了解OAuth2,可以查看链接新浪微博的说明。除了app key和app secret外,OAuth2授权参数还需要网站回调地址redirect_uri,这个回调地址不允许在局域网内(神马localhost,127.< @0.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人工客服


线