新浪微博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('', '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=''):
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('', '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('', '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()
新浪微博Python客户端接口OAuth2的更多相关文章
- 新浪微博Python3客户端接口OAuth2
Keyword: Python3 Oauth2 新浪微博 本接口基于廖雪峰的weibo python SDK修改完成,其sdk为新浪官方所推荐,原作者是用python2写的 经过一些修改,这里提供基于 ...
- python+request接口自动化框架
python+request接口自动化框架搭建 1.数据准备2.用python获取Excel文件中测试用例数据3.通过requests测试接口4.根据接口返回的code值和Excel对比 但本章只讲整 ...
- thrift例子:python客户端/java服务端
java服务端的代码请看上文. 1.说明: 这两篇文章其实解决的问题是,当使用python去访问大数据线上集群的时候,遇到两个问题: 1)python-hadoop和python-hive相关包链接不 ...
- python定义接口继承类
zxq547 python定义接口继承类invalid syntax解决办法 1 2 3 4 5 6 7 class s_all(metaclass=abc.ABCMeta): #python ...
- Redis的Python客户端redis-py的初步使用
1. Redis的安装 sudo pip install redis sudo pip install hiredis Parser可以控制如何解析redis响应的内容.redis-py包含两个Par ...
- 新浪微博iOS客户端架构与优化之路
新浪微博iOS客户端架构与优化之路 随着Facebook.Twitter.微博的崛起,向UGC.PGC.OGC,自媒体提供平台的内 容消费型App逐渐形成了独特的客户端架构模式.与电商和通讯工具类 ...
- cxf的使用及安全校验-02创建简单的客户端接口
上一篇文章中,我们已经讲了如果简单的创建一个webservice接口 http://www.cnblogs.com/snowstar123/p/3395568.html 现在我们创建一个简单客户端接口 ...
- Warensoft Stock Service Api客户端接口说明
Warensoft Stock Service Api客户端接口说明 Warensoft Stock Service Api Client Reference 可使用环境(Available Envi ...
- HBase新的客户端接口
最近学习接触HBase的东西,看了<Habase in Action>,但里面关于HBase接口都是过时的接口,以下为HBase新的客户端接口: package com.n10k; imp ...
随机推荐
- [Angular2 Animation] Control Undefined Angular 2 States with void State
Each trigger starts with an “undefined” state or a “void” state which doesn’t match any of your curr ...
- 【LeetCode-面试算法经典-Java实现】【104-Maximum Depth of Binary Tree(二叉树的最大深度)】
[104-Maximum Depth of Binary Tree(二叉树的最大深度)] [LeetCode-面试算法经典-Java实现][全部题目文件夹索引] 原题 Given a binary t ...
- ImageButton按压效果失效
LinearLayout中ImageButton的按压效果不起作用,如图 布局如下: <LinearLayout android:id="@id/ll_add_reply_face&q ...
- Lucene学习总结之七:Lucene搜索过程解析 2014-06-25 14:23 863人阅读 评论(1) 收藏
一.Lucene搜索过程总论 搜索的过程总的来说就是将词典及倒排表信息从索引中读出来,根据用户输入的查询语句合并倒排表,得到结果文档集并对文档进行打分的过程. 其可用如下图示: 总共包括以下几个过程: ...
- php实现把二叉树打印成多行(谋而后动,写好算法思路,不然浪费超多时间而且还是错误代码,而且精力消耗会导致代码正确率下降以及低级错误)
php实现把二叉树打印成多行(谋而后动,写好算法思路,不然浪费超多时间而且还是错误代码,而且精力消耗会导致代码正确率下降以及低级错误) 一.总结 要点:a.层次遍历(队列) b.层次遍历中的层次(孩 ...
- Android自定义组件系列【7】——进阶实践(4)
上一篇<Android自定义组件系列[6]--进阶实践(3)>中补充了关于Android中事件分发的过程知识,这一篇我们接着来分析任老师的<可下拉的PinnedHeaderExpan ...
- 【42.07%】【codeforces 558A】Lala Land and Apple Trees
time limit per test1 second memory limit per test256 megabytes inputstandard input outputstandard ou ...
- ArcEngine 图层标注 (根据字段、角度)
转自chanyinhelv原文 ArcEngine 图层标注 (根据字段.角度) 今天做了一个用AE来控制图层是否显示标注,以及已哪一个字段作为标注的字段,以哪一个字段作为标注的角度,现将代码写下来, ...
- [CSS Flex] Flex direction
flex-direction: main two 'row' or 'column', you can use reverse also.
- 开源 免费 java CMS - FreeCMS1.9 会员管理
项目地址:http://www.freeteam.cn/ 会员管理 1. 会员管理 从左側管理菜单点击会员管理进入. 2. 加入会员 在会员列表下方点击"加入"button. 填写 ...