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的更多相关文章

  1. 新浪微博Python3客户端接口OAuth2

    Keyword: Python3 Oauth2 新浪微博 本接口基于廖雪峰的weibo python SDK修改完成,其sdk为新浪官方所推荐,原作者是用python2写的 经过一些修改,这里提供基于 ...

  2. python+request接口自动化框架

    python+request接口自动化框架搭建 1.数据准备2.用python获取Excel文件中测试用例数据3.通过requests测试接口4.根据接口返回的code值和Excel对比 但本章只讲整 ...

  3. thrift例子:python客户端/java服务端

    java服务端的代码请看上文. 1.说明: 这两篇文章其实解决的问题是,当使用python去访问大数据线上集群的时候,遇到两个问题: 1)python-hadoop和python-hive相关包链接不 ...

  4. python定义接口继承类

    zxq547 python定义接口继承类invalid syntax解决办法 1 2 3 4 5 6 7 class s_all(metaclass=abc.ABCMeta):     #python ...

  5. Redis的Python客户端redis-py的初步使用

    1. Redis的安装 sudo pip install redis sudo pip install hiredis Parser可以控制如何解析redis响应的内容.redis-py包含两个Par ...

  6. 新浪微博iOS客户端架构与优化之路

    新浪微博iOS客户端架构与优化之路   随着Facebook.Twitter.微博的崛起,向UGC.PGC.OGC,自媒体提供平台的内 容消费型App逐渐形成了独特的客户端架构模式.与电商和通讯工具类 ...

  7. cxf的使用及安全校验-02创建简单的客户端接口

    上一篇文章中,我们已经讲了如果简单的创建一个webservice接口 http://www.cnblogs.com/snowstar123/p/3395568.html 现在我们创建一个简单客户端接口 ...

  8. Warensoft Stock Service Api客户端接口说明

    Warensoft Stock Service Api客户端接口说明 Warensoft Stock Service Api Client Reference 可使用环境(Available Envi ...

  9. HBase新的客户端接口

    最近学习接触HBase的东西,看了<Habase in Action>,但里面关于HBase接口都是过时的接口,以下为HBase新的客户端接口: package com.n10k; imp ...

随机推荐

  1. 6、USB Video Class Specification

    关于USB Class 将设备归为既定的类别,并对相应类别的设备的在USB协议的应用级协议和接口作出规范,这样只要按照类设备的标准实现驱动程序和设备,则一套驱动可以驱动这一类的所有设备,而这一类设备可 ...

  2. [RxJS] Implement pause and resume feature correctly through RxJS

    Eventually you will feel the need for pausing the observation of an Observable and resuming it later ...

  3. 【Python排序搜索基本算法】之拓扑排序

    拓扑排序是对有向无环图的一种排序,满足例如以下两个条件: 1.每一个顶点出现且仅仅出现一次. 2.若A在序列中排在B的前面.则在图中不存在从B到A的路径. 如上的无环有向图,v表示顶点:v=['a', ...

  4. 【77.78%】【codeforces 625C】K-special Tables

    time limit per test 2 seconds memory limit per test 256 megabytes input standard input output standa ...

  5. 几种常见web 容器比较 (tomcat、 jboss 、resin、 weblogic、 websphere、 glassfish)(转)

    点击打开PDF下载链接 web 容器比较 tomcat jboss resin weblogic websphere glassfish 1. Tomcat是Apache鼎力支持的Java Web应用 ...

  6. 在Linux上安装及配置MariaDB

    安装MariaDB 1.切换到root用户,首先执行rpm -qa | grep -i mysql检查一下是否有已安装的与MySQL相关的东西,如果有,使用rpm -e --nodeps mysql* ...

  7. Android JNI编程(一)——JNI概念以及C语言Dev-C++开发环境搭建、编写HelloWorld

    版权声明:本文出自阿钟的博客,转载请注明出处:http://blog.csdn.net/a_zhon/. 目录(?)[+] 一:JNI是什么呢? JNI:JNI是JavaNative Interfac ...

  8. 小强的HTML5移动开发之路(48)——(小练习)新闻订阅系统【1】

    一.总体设计 二.数据库设计 --新闻类别表 create table news_cate( news_cateid int primary key auto_increment, news_icon ...

  9. Windows Phone 8.1 控件

    如果你已经开始了 Windows Phone 8.1 的学习,就会发现许多在 8.0 下的控件在 8.1 中都发生了变化,以下就谈谈几个 8.1 下的新控件以及与 8.0 控件的改变. 1. Text ...

  10. 一起学Python:tcp服务器

    tcp服务器 生活中的电话机 如果想让别人能更够打通咱们的电话获取相应服务的话,需要做以下几件事情: 买个手机 插上手机卡 设计手机为正常接听状态(即能够响铃) 静静的等着别人拨打 tcp服务器 如同 ...