Home » Python » 有道云笔记OpenAPI接口Python版
  • 30
  • 11月

很早之前看到有道云笔记的OpenAPI,之后就申请了,但是很久没有看到有回复。今天打开邮件一看,竟然审批通过了。

有道云笔记个人应用审核通过

所以今天心血来潮,花了一天时间,写了个Python版的OpenAPI,主要接口都实现了,分享、附件、图片这些暂且就懒得弄了。

OpenAPI文档参考:http://notesandbox.youdao.com/open/apidoc.html

论坛里的相关帖子真是太少了,有关OpenAPI才11个主题,不得不吐槽一下~

下面贴代码吧,学Python的应该都看得懂滴~~

# -*- encoding: utf-8 -*-

"""
    Youdao Note OpenAPI
    ~~~~~~~~~~~~~~~~~~~

    Youdao Note OpenAPI
    see <http://notesandbox.youdao.com/open/apidoc.html> for more details.

    :copyright: (c) 2013 by digwtx <wtx358@qq.com>.
    :license: GPL v3
"""

import time
import json
import urllib
import urllib2
import httplib

# consumerKey
CK = ''
# consumerSecret
CS = ''

BASE_URL = 'notesandbox.youdao.com'

REDIRECT_CODE_URL = 'http://digwtx.duapp.com'
REDIRECT_TOKEN_URL = 'http://digwtx.duapp.com'

OAUTH_AUTHORIZE_URL = '/oauth/authorize2'
OAUTH_ACCESS_URL = '/oauth/access2'

USER_GET_URL = '/yws/open/user/get.json'

NOTEBOOK_ALL_URL = '/yws/open/notebook/all.json'
NOTEBOOK_CREATE_URL = '/yws/open/notebook/create.json'
NOTEBOOK_DELETE_URL = '/yws/open/notebook/delete.json'

NOTE_LIST_URL = '/yws/open/notebook/list.json'
NOTE_GET_URL = '/yws/open/note/get.json'
NOTE_MOVE_URL = '/yws/open/note/move.json'
NOTE_UPDATE_URL = '/yws/open/note/update.json'
NOTE_CREATE_URL = '/yws/open/note/create.json'
NOTE_DELETE_URL = '/yws/open/note/delete.json'

token = ''

def _encode_multipart(params_dict):
    """Build a multipart/form-data body with generated random boundary."""
    data = []
    boundary = '----------%s' % hex(int(time.time() * 1000))

    for k, v in params_dict.items():
        data.append('--%s' % boundary)
        if hasattr(v, 'read'):
            filename = getattr(v, 'name', '')
            content = v.read()
            decoded_content = content.decode('ISO-8859-1')
            data.append('Content-Disposition: form-data; name="%s"; filename="hidden"' % k)
            data.append('Content-Type: application/octet-stream\r\n')
            data.append(decoded_content)
        else:
            data.append('Content-Disposition: form-data; name="%s"\r\n' % k)
            data.append(v if isinstance(v, str) else v.decode('utf-8'))
    data.append('--%s--\r\n' % boundary)
    return '\r\n'.join(data), boundary


def do_request(host=None, url=None, method='GET', headers={}, params={}):
    if isinstance(params, dict):
        params = urllib.urlencode(params)
    conn = httplib.HTTPSConnection(host)
    conn.request(method=method, url=url, body=params, headers=headers)
    response = conn.getresponse()
    return response


class YoudaoNoteOauth2(object):
    """ Oauth 2.0 """
    def __init__(self):
        pass

    def get_code(self):
        """请求用户登陆授权"""
        params = {
            'client_id': CK,
            'response_type': 'code',
            'redirect_uri': REDIRECT_CODE_URL,
            'state': '31415926',
        }

        url = 'https://%s%s?%s' % (BASE_URL, OAUTH_AUTHORIZE_URL,
                                   urllib.urlencode(params))
        return url

    def get_token(self, code):
        """获取AccessToken"""
        params = {
            'client_id': CK,
            'client_secret': CS,
            'grant_type': 'authorization_code',
            'redirect_uri': REDIRECT_TOKEN_URL,
            'code': code,
        }

        try:
            url = 'https://%s%s?%s' % (BASE_URL, OAUTH_ACCESS_URL,
                                       urllib.urlencode(params))
            response = urllib.urlopen(url)
            token = json.loads(response.read())['accessToken']
            return token
        except Exception as e:
            print e
            return None


class YoudaoNoteApi(object):
    """有道云笔记 OpenAPI"""

    def __init__(self, token):
        self.token = token

    def user_get(self):
        """获取用户基本信息"""

        headers = {"Authorization": 'OAuth oauth_token="%s"' % self.token}

        response = do_request(BASE_URL, USER_GET_URL,
                              headers=headers)

        status = response.status
        res_dict = json.loads(response.read())
        return (status, res_dict)

    def notebook_all(self):
        """查看用户全部笔记本"""

        headers = {"Authorization": 'OAuth oauth_token="%s"' % self.token}

        response = do_request(BASE_URL, NOTEBOOK_ALL_URL, method='POST',
                              headers=headers)

        status = response.status
        res_dict = json.loads(response.read())
        return (status, res_dict)

    def notebook_create(self, name):
        """创建笔记本"""

        params = {'name': name}
        headers = {
            "Authorization": 'OAuth oauth_token="%s"' % self.token,
            "Content-Type": "application/x-www-form-urlencoded"
        }

        response = do_request(BASE_URL, NOTEBOOK_CREATE_URL, method='POST',
                              headers=headers, params=params)

        status = response.status
        data = response.read()
        res_dict = json.loads(data)
        return (status, res_dict)

    def notebook_delete(self, notebook):
        """删除笔记本"""

        params = {'notebook': notebook}
        headers = {
            "Authorization": 'OAuth oauth_token="%s"' % self.token,
            "Content-Type": "application/x-www-form-urlencoded"
        }

        response = do_request(BASE_URL, NOTEBOOK_DELETE_URL, method='POST',
                              headers=headers, params=params)

        status = response.status
        data = response.read()
        if status == 200:
            return (status, )
        else:
            res_dict = json.loads(data)
            return (status, res_dict)

    def note_list(self, notebook):
        """列出笔记本下的笔记"""

        params = {'notebook': notebook}
        headers = {
            "Authorization": 'OAuth oauth_token="%s"' % self.token,
            "Content-Type": "application/x-www-form-urlencoded"
        }

        response = do_request(BASE_URL, NOTE_LIST_URL, method='POST',
                              headers=headers, params=params)

        status = response.status
        res_dict = json.loads(response.read())
        return (status, res_dict)

    def note_get(self, path):
        """查看笔记"""

        params = {'path': path}
        headers = {
            "Authorization": 'OAuth oauth_token="%s"' % self.token,
            "Content-Type": "application/x-www-form-urlencoded"
        }

        response = do_request(BASE_URL, NOTE_GET_URL, method='POST',
                              headers=headers, params=params)

        status = response.status
        res_dict = json.loads(response.read())
        return (status, res_dict)

    def note_create(self, params_dict):
        """创建笔记"""

        body, boundary = _encode_multipart(params_dict)

        headers = {
            "Authorization": 'OAuth oauth_token="%s"' % self.token,
            "Content-Type": 'multipart/form-data; boundary=%s' % boundary,
        }

        response = do_request(BASE_URL, NOTE_CREATE_URL, method='POST',
                              headers=headers, params=body)

        status = response.status
        res_dict = json.loads(response.read())
        return (status, res_dict)

    def note_update(self, params_dict):
        """修改笔记"""

        body, boundary = _encode_multipart(params_dict)

        headers = {
            "Authorization": 'OAuth oauth_token="%s"' % self.token,
            "Content-Type": 'multipart/form-data; boundary=%s' % boundary,
        }

        response = do_request(BASE_URL, NOTE_UPDATE_URL, method='POST',
                              headers=headers, params=body)

        status = response.status
        if status == 200:
            return (status, )
        else:
            res_dict = json.loads(response.read())
            return (status, res_dict)

    def note_move(self, path, notebook):
        """移动笔记"""

        params = {'path': path, 'notebook': notebook}
        headers = {
            "Authorization": 'OAuth oauth_token="%s"' % self.token,
            "Content-Type": "application/x-www-form-urlencoded"
        }

        response = do_request(BASE_URL, NOTE_MOVE_URL, method='POST',
                              headers=headers, params=params)

        status = response.status
        res_dict = json.loads(response.read())
        return (status, res_dict)

    def note_delete(self, path):
        """删除笔记"""

        params = {'path': path}
        headers = {
            "Authorization": 'OAuth oauth_token="%s"' % self.token,
            "Content-Type": "application/x-www-form-urlencoded"
        }

        response = do_request(BASE_URL, NOTE_DELETE_URL, method='POST',
                              headers=headers, params=params)

        status = response.status
        data = response.read()
        if status == 200:
            return (status, )
        else:
            res_dict = json.loads(data)
            return (status, res_dict)

ydauth = YoudaoNoteOauth2()
print "open this url in your browser, and get the code from the redirect_url:"
print ydauth.get_code()
code = raw_input("input the code:")
token = ydauth.get_token(code)

yd = YoudaoNoteApi(token)

print yd.user_get()
print yd.notebook_all()