新浪微博Python客户端接口OAuth2

Keyword: Python Oauth2 微博 sina weibo

 

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

__version__ = '1.04'
__author__ = 'Liao Xuefeng (askxuefeng@gmail.com)'

'''
Python client SDK for sina weibo API using OAuth 2.
'''

try:
    import json
except ImportError:
    import simplejson as json
import time
import urllib
import urllib2
import logging

def _obj_hook(pairs):
    '''
    convert json object to python object.
    '''
    o = JsonObject()
    for k, v in pairs.iteritems():
        o[str(k)] = v
    return o

class APIError(StandardError):
    '''
    raise APIError if got failed json message.
    '''
    def __init__(self, error_code, error, request):
        self.error_code = error_code
        self.error = error
        self.request = request
        StandardError.__init__(self, error)

    def __str__(self):
        return 'APIError: %s: %s, request: %s' % (self.error_code, self.error, self.request)

class JsonObject(dict):
    '''
    general json object that can bind any fields but also act as a dict.
    '''
    def __getattr__(self, attr):
        return self[attr]

    def __setattr__(self, attr, value):
        self[attr] = value

def _encode_params(**kw):
    '''
    Encode parameters.
    '''
    args = []
    for k, v in kw.iteritems():
        qv = v.encode('utf-8') if isinstance(v, unicode) else str(v)
        args.append('%s=%s' % (k, urllib.quote(qv)))
    return '&'.join(args)

def _encode_multipart(**kw):
    '''
    Build a multipart/form-data body with generated random boundary.
    '''
    boundary = '----------%s' % hex(int(time.time() * 1000))
    data = []
    for k, v in kw.iteritems():
        data.append('--%s' % boundary)
        if hasattr(v, 'read'):
            # file-like object:
            ext = ''
            filename = getattr(v, 'name', '')
            n = filename.rfind('.')
            if n != (-1):
                ext = filename[n:].lower()
            content = v.read()
            data.append('Content-Disposition: form-data; name="%s"; filename="hidden"' % k)
            data.append('Content-Length: %d' % len(content))
            data.append('Content-Type: %s\r\n' % _guess_content_type(ext))
            data.append(content)
        else:
            data.append('Content-Disposition: form-data; name="%s"\r\n' % k)
            data.append(v.encode('utf-8') if isinstance(v, unicode) else v)
    data.append('--%s--\r\n' % boundary)
    return '\r\n'.join(data), boundary

_CONTENT_TYPES = { '.png': 'image/png', '.gif': 'image/gif', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.jpe': 'image/jpeg' }

def _guess_content_type(ext):
    return _CONTENT_TYPES.get(ext, 'application/octet-stream')

_HTTP_GET = 0
_HTTP_POST = 1
_HTTP_UPLOAD = 2

def _http_get(url, authorization=None, **kw):
    logging.info('GET %s' % url)
    return _http_call(url, _HTTP_GET, authorization, **kw)

def _http_post(url, authorization=None, **kw):
    logging.info('POST %s' % url)
    return _http_call(url, _HTTP_POST, authorization, **kw)

def _http_upload(url, authorization=None, **kw):
    logging.info('MULTIPART POST %s' % url)
    return _http_call(url, _HTTP_UPLOAD, authorization, **kw)

def _http_call(url, method, authorization, **kw):
    '''
    send an http request and expect to return a json object if no error.
    '''
    params = None
    boundary = None
    if method==_HTTP_UPLOAD:
        params, boundary = _encode_multipart(**kw)
    else:
        params = _encode_params(**kw)
    http_url = '%s?%s' % (url, params) if method==_HTTP_GET else url
    http_body = None if method==_HTTP_GET else params
    req = urllib2.Request(http_url, data=http_body)
    if authorization:
        req.add_header('Authorization', 'OAuth2 %s' % authorization)
    if boundary:
        req.add_header('Content-Type', 'multipart/form-data; boundary=%s' % boundary)
    resp = urllib2.urlopen(req)
    body = resp.read()
    r = json.loads(body, object_hook=_obj_hook)
    if hasattr(r, 'error_code'):
        raise APIError(r.error_code, getattr(r, 'error', ''), getattr(r, 'request', ''))
    return r

class HttpObject(object):

    def __init__(self, client, method):
        self.client = client
        self.method = method

    def __getattr__(self, attr):
        def wrap(**kw):
            if self.client.is_expires():
                raise APIError('21327', 'expired_token', attr)
            return _http_call('%s%s.json' % (self.client.api_url, attr.replace('__', '/')), self.method, self.client.access_token, **kw)
        return wrap

class APIClient(object):
    '''
    API client using synchronized invocation.
    '''
    def __init__(self, app_key, app_secret, redirect_uri=None, response_type='code', domain='api.weibo.com', version='2'):
        self.client_id = app_key
        self.client_secret = app_secret
        self.redirect_uri = redirect_uri
        self.response_type = response_type
        self.auth_url = 'https://%s/oauth2/' % domain
        self.api_url = 'https://%s/%s/' % (domain, version)
        self.access_token = None
        self.expires = 0.0
        self.get = HttpObject(self, _HTTP_GET)
        self.post = HttpObject(self, _HTTP_POST)
        self.upload = HttpObject(self, _HTTP_UPLOAD)

    def set_access_token(self, access_token, expires_in):
        self.access_token = str(access_token)
        self.expires = float(expires_in)

    def get_authorize_url(self, redirect_uri=None, display='default'):
        '''
        return the authroize url that should be redirect.
        '''
        redirect = redirect_uri if redirect_uri else self.redirect_uri
        if not redirect:
            raise APIError('21305', 'Parameter absent: redirect_uri', 'OAuth2 request')
        return '%s%s?%s' % (self.auth_url, 'authorize', \
                _encode_params(client_id = self.client_id, \
                        response_type = 'code', \
                        display = display, \
                        redirect_uri = redirect))

    def request_access_token(self, code, redirect_uri=None):
        '''
        return access token as object: {"access_token":"your-access-token","expires_in":12345678}, expires_in is standard unix-epoch-time
        '''
        redirect = redirect_uri if redirect_uri else self.redirect_uri
        if not redirect:
            raise APIError('21305', 'Parameter absent: redirect_uri', 'OAuth2 request')
        r = _http_post('%s%s' % (self.auth_url, 'access_token'), \
                client_id = self.client_id, \
                client_secret = self.client_secret, \
                redirect_uri = redirect, \
                code = code, grant_type = 'authorization_code')
        r.expires_in += int(time.time())
        return r

    def is_expires(self):
        return not self.access_token or time.time() > self.expires

    def __getattr__(self, attr):
        return getattr(self.get, attr)

def main():
    try:
        #step 1 定义 app key,app secret,回调地址:
        APP_KEY = "14752459xx"
        APP_SECRET = "7be6f636faf7b17d048c0cd3c55adaxx"
        CALLBACK_URL = 'http://api.doucube.com/oauth2/default.html'
        #step 2 引导用户到授权地址
        client = APIClient(app_key=APP_KEY, app_secret=APP_SECRET, redirect_uri=CALLBACK_URL)
        print client.get_authorize_url()
        #step 3 换取Access Token
        r = client.request_access_token(raw_input("Input CODE:"))#输入授权地址中获得的CODE
        client.set_access_token(r.access_token, r.expires_in)
        #step 4 使用获得的OAuth2.0 Access Token调用API
        print client.get.account__get_uid()
        print client.post.statuses__update(status=u'测试Python + OAuth 2.0发微博')
        print client.upload.statuses__upload(status=u'测试Python + OAuth 2.0带图片发微博', pic=open('test.jpg'))

    except Exception as pyOauth2Error:
        print pyOauth2Error

if __name__ == '__main__':
    main()

 

时间: 2024-11-22 20:53:47

新浪微博Python客户端接口OAuth2的相关文章

新浪微博Python3客户端接口OAuth2

Keyword: Python3 Oauth2 新浪微博 本接口基于廖雪峰的weibo python SDK修改完成,其sdk为新浪官方所推荐,原作者是用python2写的 经过一些修改,这里提供基于python3的 weibo SDK     #!/usr/bin/env python # -*- coding: utf-8 -*- __version__ = '1.04' __author__ = 'Liao Xuefeng (askxuefeng@gmail.com)' __publish

oauth-利用新浪的python sdk接口时,需要OAuth2.0认证,如何模拟获取code码

问题描述 利用新浪的python sdk接口时,需要OAuth2.0认证,如何模拟获取code码 我在使用新浪的python sdk接口时,涉及OAuth2.0认证,其中要获取code码.如何用程序模拟授权,然后获取code码?

新浪微博api 调用-怎么调用新浪微博API开放接口发图片微博

问题描述 怎么调用新浪微博API开放接口发图片微博 我的代码如下,发文字的可以,发图片微博却不行,怎么总是返回400,求解答,他要求图片需要传入binary类型 string url = "https://upload.api.weibo.com/2/statuses/upload.json"; string usernamePassword = UserName + ":" + PassWord; string t_news = string.Format(&qu

初识Django —Python API接口编程入门

初识Django -Python API接口编程入门 一.WEB架构的简单介绍 Django是什么? Django是一个开放源代码的Web应用框架,由Python写成.我们的目标是用Python语言,基于Django框架,利用MVC模型,实现后台方面的针对数据库的API开发.先了解一下互联网的WEB架构, 如上图: 互联网的WEB架构大致分为三层,web层.app层和数据库层.Web层:如apache网站服务器:app层主要是应用业务:DB指后台数据库.随着互联网的高速发展,网站访问量的增长.数

新浪微博android客户端 底部导航消息一栏是否是用的viewpager控件展示的?

问题描述 新浪微博android客户端 底部导航消息一栏是否是用的viewpager控件展示的? 如标题... 每个页面的数据 异步加载是如何进行的 ... .. 解决方案 私认为是通过Fragment结合TabHost实现的.每个页面用一个Fragment管理. 解决方案二: 猜ViewPage+Fragment

fastdfs python客户端fdfs_client_py上传从文件问题

问题描述 fastdfs python客户端fdfs_client_py上传从文件问题 有人用过fdfs的python 客户端fdfs_client_py上传文件吗?我的代码如下: def upload_file(self,filePath=None,slaveFilePath=None): #upload the apk and the apk details html file into fastdfs storage #apk file as master file while html

人机交互-怎么在安卓客户端接口接收智能硬件所发出的数据?

问题描述 怎么在安卓客户端接口接收智能硬件所发出的数据? 各位大神,本人小白,本人在设计android系统的APP时怎么在代码中插入智能硬件所发出的数据,实现人机交互的功能?望各位大神指点迷津!!! 解决方案 Socket通信,蓝牙,wifi,到时候直接读数据就Ok

新浪微博ios客户端的搜索界面是怎么写出来的

问题描述 新浪微博ios客户端的搜索界面是怎么写出来的

《Ceph源码分析》——第1章,第4节Ceph客户端接口

1.4 Ceph客户端接口Ceph的设计初衷是成为一个分布式文件系统,但随着云计算的大量应用,最终变成支持三种形式的存储:块存储.对象存储.文件系统,下面介绍它们之间的区别. 1.4.1 RBDRBD(rados block device)是通过librbd库对应用提供块存储,主要面向云平台的虚拟机提供虚拟磁盘.传统SAN就是块存储,通过SCSI或者FC接口给应用提供一个独立的LUN或者卷.RBD类似于传统的SAN存储,都提供数据块级别的访问.目前RBD提供了两个接口,一种是直接在用户态实现,通