返回

Python访问Google Keep个人数据:OAuth授权实战指南

python

使用 Python 访问个人 Google Keep 数据

Google Keep 是一款便利的笔记应用。有些开发者希望能通过编程方式与其互动,实现诸如数据同步、备份或者自动化处理等操作。 本文探讨如何通过 Python 访问个人 Google Keep 数据,并着重讲解遇到的常见问题及解决方案。

问题:Service Account 访问失败

常见的误解是使用服务帐号来直接访问个人用户数据。虽然服务帐号在 Google Cloud 中具有很强的授权能力,它们的设计初衷是用于应用程序服务与 Google Cloud Platform 产品互动,而非直接代理用户执行操作。因此,即使在 Google Keep 笔记中添加服务帐号为协作者,服务帐号依然无法通过 API 直接读取个人用户数据。 这是由于服务帐户本质上代表服务,而非具体的个人用户,而 API 授权的控制力度非常严格,以避免隐私和安全问题。

代码示例:

from google.oauth2 import service_account
from googleapiclient.discovery import build

SCOPES = ['https://www.googleapis.com/auth/keep']
SERVICE_ACCOUNT_FILE = 'credentials.json'

credentials = service_account.Credentials.from_service_account_file(
    SERVICE_ACCOUNT_FILE,
    scopes=SCOPES
)

service = build("keep", "v1", credentials=credentials)
l = service.notes().list().execute()
print(l)

上述代码使用服务帐户证书建立连接并调用 Keep API,期望返回用户的数据。由于权限原因,实际运行时通常会返回一个空的字典。 这符合 API 的预期行为,反映服务帐号无法代表用户去请求个人 Keep 数据的事实。

解决方案:使用 OAuth 2.0 用户凭证

与服务帐户不同,OAuth 2.0 用户凭证代表一个特定用户,因此它才能够授权用户访问个人数据。获取 OAuth 2.0 用户凭证的过程比服务账户要稍微复杂一些,它通常涉及到:创建项目、设置 OAuth 同意屏幕、获取 client_id 与 client_secret 等信息。同时用户需要亲自同意授权,从而授权应用程序代表其操作。

获取 OAuth 2.0 用户凭证

  1. 在 Google Cloud Console 创建一个项目。
  2. 在 “API & 服务” 中启用 Google Keep API。
  3. 在 "API & 服务 > 凭据" 创建 OAuth 2.0 客户端 ID。注意应用程序类型选择"桌面应用"。
  4. 下载 credentials.json,包含了 client_id, client_secret 等必要的信息。
  5. 执行以下 Python 代码:
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build

SCOPES = ['https://www.googleapis.com/auth/keep']
CLIENT_SECRET_FILE = 'credentials.json'


def get_credentials():
    creds = None
    # The file token.json stores the user's access and refresh tokens
    if os.path.exists('token.json'):
        creds = Credentials.from_token_file('token.json', SCOPES)
    # If there are no (valid) credentials available, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                CLIENT_SECRET_FILE, SCOPES)
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open('token.json', 'w') as token:
            token.write(creds.to_json())
    return creds


if __name__ == '__main__':
    creds = get_credentials()
    service = build('keep', 'v1', credentials=creds)
    l = service.notes().list().execute()
    print(l)

代码步骤分解:

  • InstalledAppFlow: 使用本地应用授权流,更适用于桌面程序。
  • 第一次运行 flow.run_local_server(port=0) 会弹出一个网页,需要用户同意授权,程序得到 access_token
  • access_token 有效期有限,需要 refresh_token 定期刷新,所以我们将用户信息保存为 token.json 。下次运行时可以直接从这个文件加载凭据。

执行这个代码时,会提示需要用户授权访问你的 Google Keep 数据。请按照提示完成操作,授权成功后就能返回用户真实的 Keep 数据了。这个方法完全以用户行为为基础进行授权,充分尊重用户的个人隐私。

额外的安全建议

  • 保护好 credentials.json 文件,以及 token.json ,避免泄露。这两个文件一旦泄露可能会被恶意利用。
  • token.json 加入 .gitignore 防止它被上传到公共代码仓库。

使用 OAuth 2.0 用户凭证是访问个人 Google Keep 数据的正确方法。通过详细步骤与代码演示,用户应该能成功调用 Google Keep API 获取到个人的笔记数据。选择适当的授权方式是安全且有效地使用 API 的前提,这样既满足了开发者需求,也能保障个人数据隐私安全。