使用新浪微博开放平台api同步微博内容至自己网站(这里有新鲜出炉的Python入门,程序狗速度看过来! )
优采云 发布时间: 2021-12-17 04:00使用新浪微博开放平台api同步微博内容至自己网站(这里有新鲜出炉的Python入门,程序狗速度看过来!
)
这里有新鲜的Python介绍,看程序狗的速度!
Python编程语言 Python是一种面向对象的解释型计算机编程语言,由Guido van Rossum于1989年底发明,1991年首次公开发布。Python语法简洁明了,具有丰富而强大的类库. 它通常被称为胶水语言,它可以很容易地将其他语言(尤其是 C/C++)制作的各种模块连接在一起。
本文介绍了python连接新浪微博开放平台的方法。请有需要的同学参考。另外,官方新浪微博开放平台有完整的SDK和帮助文档,有需要的同学可以自行查看。
因为最近接触到一个调用新浪微博开放接口的项目,想尝试用python调用微博API。有需要的朋友可以参考以下
因为最近接触到调用新浪微博开放接口的项目,想尝试用python调用微博API。
SDK下载地址:代码不超过十几K,完全可以理解。
如果你有微博账号,你可以创建一个新的应用程序,然后你就可以得到应用程序密钥和应用程序密钥。这是应用获得 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!')
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 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