python新浪微博认证及发微

新浪微博认证需要安装新浪微博的API(Python),安装好后就可以使用微博提供的的各种接口。这里只简单介绍认证和发微。·

首先可以通过微博开放平台注册应用申请APP_KEY和APP_SECRET,它们是认证所必须的。(无需审核已经可以用很多接口了)

新浪微博开放平台:http://open.weibo.com/

例如我的应用:

设置OAuth2认证的回调地址,这里我设置了默认地址:(回调地址用来接收认证成功的准入序列号)


OAuth2认证过程如下图:


以下是login.py登陆认证模块,返回OAuth2认证成功的APIClient对象:

#login module
import urllib
import urllib2
import sys
from weibo import APIClient
import myConfig as con

def login():
    client = APIClient(app_key=con.APP_KEY, app_secret=con.APP_SECRET, redirect_uri=con.CALLBACK_URL)
    # get authorization url (resource owner)
    referer_url = client.get_authorize_url()
    # print referer_url
    cookies = urllib2.HTTPCookieProcessor()
    opener = urllib2.build_opener(cookies)
    urllib2.install_opener(opener)

    postdata = {
            "client_id": con.APP_KEY,
            "redirect_uri": con.CALLBACK_URL,
            "userId": con.USERID,
            "passwd": con.PASSWD,
            "isLoginSina": "0",
            "action": "submit",
            "response_type": "code"
    }

    headers = {
           "User-Agent":"Guess",
           "Host":"api.weibo.com",
           "Referer":referer_url
    }

    req = urllib2.Request(
    	        url=referer_url,
    	        data=urllib.urlencode(postdata),
    	        headers=headers
    	)
    try:
        # get authorization grant
    	resp=urllib2.urlopen(req)
        # print resp.geturl()

        # get request code for access token
    	code=resp.geturl()[-32:]

        # get access token
    	r=client.request_access_token(code)

    	client.set_access_token(r.access_token, r.expires_in)
    	print "login success!"
    	return client
    except Exception, e:
    	print "login error!"
    	print e
其中myConfig是我的配置文件:

APP_KEY = 'xxxxxxxxx'
APP_SECRET = 'xxxxxxxxxxxxxxxxxxxxxxxxxxx'
CALL_BACK = 'https://api.weibo.com/oauth2/default.html'
CALLBACK_URL = 'https://api.weibo.com/oauth2/default.html'
USERID = 'username'
PASSWD = 'password'

如果认证成功,那么就可以通过该APIClient对象进行一系列的操作,最基本的如发送微博:

client.statuses.upload.post(status='love is a beauty')




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值