使用Python编写客户端 上传文字or图片至新浪微博 by OAuth 2.0

本文介绍了如何使用PythonSDK实现微博的OAuth2.0认证流程,并提供了完整的代码示例。重点包括配置API密钥、获取访问令牌、执行API调用等关键步骤,同时解决了在上传图片时抛出的HTTPERROR503异常问题。

此链接为新浪微博推荐的Python SDK:https://github.com/michaelliao/sinaweibopy/wiki/OAuth2-HOWTO

Python SDK 介绍:http://michaelliao.github.com/sinaweibopy/

此链接为使用OAuth 1.0 实现的:http://blog.youkuaiyun.com/presidentpresident/article/details/7555979

以下是OAuth 2.0 实现代码:

# -*- coding:utf-8 -*- #
#! /usr/bin/env python

from weibo import *
    
def send_sina_weibo():

    APP_KEY = '77734XXXX'
    APP_SECRET = '5fa146e5e4a590523969c3de2e7xxxxx'

    CALLBACK_URL = 'https://api.weibo.com/oauth2/default.html'
    client = APIClient(app_key=APP_KEY,app_secret=APP_SECRET,redirect_uri=CALLBACK_URL)
    url = client.get_authorize_url()
##    code = your.web.framework.request.get('code')
    print url
    client = APIClient(app_key=APP_KEY, app_secret=APP_SECRET, redirect_uri=CALLBACK_URL)
    
    r = client.request_access_token(raw_input("input code:").strip())
    access_token = r.access_token
    expires_in = r.expires_in
    print access_token
    print expires_in
    client.set_access_token(access_token,expires_in)

    print client.post.statuses__update(status=u'发送微博again by OAuth2.0')
    print client.get.statuses__user_timeline()
    print client.upload.statuses__upload(status=u'发送图片 by OAuth2.0', pic=open('test.gif'))

if __name__ == '__main__':
    send_sina_weibo()
运行上述代码可能会抛出异常 “HTTPERROR 503”

只要将:

pic=open('test.gif') 改为 pic=open('test.gif', 'rb')
 即可。
另外,本文参考了:http://blog.youkuaiyun.com/dyx1024/article/details/8470983

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值