使用Python操作Evernote API

2016-03-31  本文已影响1322人  LittleCoder
标题图

Evernote本身就是很好的笔记应用,其API又赋予了我们更多的自由,值得花点时间尝试。

本文将结合代码和理论,介绍如何使用这些API。

在阅读完成本文后,你将能够完成类似PackMemo的程序。

配置环境

配置Python

配置印象笔记开发环境

沙盒环境配置

沙盒账户开发者Token获取

普通账户开发者Token获取

进度确认

系统结构

印象笔记存在两种账户,以及每种账户相同的两种授权方式

授权方式

想要使用印象笔记的API,肯定需要先获得某个账户的授权(授权进入他的笔记,对于我们来说就是授权自己使用啦)

印象笔记的授权方法有两种

from evernote.api.client import EvernoteClient

devToken = "沙盒或者普通账户的Token"
client = EvernoteClient(token = devToken)

值得注意的是,并非所有授权都获得了所有的权限

后文用到的token变量即开发者Token授权方式的devToken或是OAuth方式获取的token

账户

服务 地址
沙盒 https://sandbox.evernote.com/api/DeveloperToken.action
产品 https://app.yinxiang.com/api/DeveloperToken.action

数据结构

总体而言,各数据的获取顺序为:UserStore, NoteStore -> Notebook -> Note -> Resource

关于笔记、笔记本的操作全部都是NoteStore类的方法,需要传入指向需要操作的对象的guid

获取Notebook、Note、Resource类用于读取内容与获取其guid

UserStore,用户信息

# 获取类
userStore = client.get_user_store()
# 打印用户名
print('Log in successfully as {}'.format(userStore.getUser().username))
if userStore.getUser().premiumInfo.premium: print('We are friends!')

NoteStore,笔记本仓库

# 获取类
noteStore = client.get_note_store()
# 获取笔记本数量
print('There are {} notebooks in your account'.format(len(noteStore.listNotebooks())))

Notebook,笔记本

# 打印每个笔记本的名字与guid
for notebook in self.noteStore.listNotebooks():
    notebookName = notebook.name
    notebookGuid = notebook.guid
    print('{}: {}'.format(notebookName, notebookGuid))

Note,笔记

# 列出第一个笔记本中的所有笔记的标题
notebookGuid = noteStore.listNotebooks()[0]
f = NoteStore.NoteFilter()
f.notebookGuid = notebookGuid
for note in noteStore.findNotes(token, f, 0, 999).notes:
    print(note.title)

进度确认

# 格式为
笔记本1:
    笔记1
    笔记2
笔记本2:
    笔记3
def show_notes(noteStore, notebookList=[]):
    for nb in noteStore.listNotebooks():
        if nb in notebookList or not notebookList:
        print(nb.name + ':')
        f = noteStore.NoteFilter()
        f.notebookGuid = nb.guid
        for ns in noteStore.findNotes(self.token, f, 0, 999).notes:
            print(('' if notebook else '    ') + ns.title)

具体方法的使用示范

以删除笔记操作(Function: NoteStore.deleteNote)为例演示如何阅读官方介绍,以下为官方介绍:

Function: NoteStore.deleteNote

首先,由于其为NoteStore类的方法,所以调用的方式为NoteStore.deleteNote(token, guid)

其次,token为上述的开发者Token或者OAuth获取到的token

再次,从图中第七行可以看出,guid的为GUID of the note to delete,下面是Note的介绍

Note

那么,只要获取到Note,就可以获得guid。

所以,最后一步,根据已经介绍过的印象笔记的数据结构,我们知道如果获取Note

以下为代码:

def find_note_guid(noteStore, noteName):
    for notebook in noteStore.listNotebooks():
        f = NoteStore.NoteFilter()
        f.notebookGuid = notebookGuid
        for note in noteStore.findNotes(token, f, 0, 999).notes:
            if note.title == noteName: return note.guid

noteStore.deleteNote(token, find_note_guid(noteStore, '要删除的笔记的名字'))

其余的方法相差不大,也就不一一赘述,你可以在这里找到所有你需要的东西

一些基础的方法我进行了一定的包装与简化,写了一个简单的EvernoteController,希望在你尝试的时候能够给予你一些启发。

你现在已经获得了完成文首处提到的PackMemo所需要的所有知识,可以开始尝试就自己的需求写应用了!

结束语

希望读完这篇文章能对你有帮助,有什么不足之处万望指正(鞠躬)。

有什么想法或者想要关注我的更新,欢迎来GithubStar或者Fork

160308

LittleCoder

EOF

上一篇 下一篇

猜你喜欢

热点阅读