授权 python 脚本在没有 OAuth2 用户流的情况下访问 GData API

Authorizing a python script to access the GData API without the OAuth2 user flow

我正在编写一个 python 小脚本,它将检索我的 Google 联系人列表(使用 Google Contacts API)并随机推荐一个人给我联系(自动与朋友保持联系的好方法!)

这只是我计划在 cron 作业上安排的独立脚本。问题是 Google 似乎需要 OAuth2 样式的身份验证,用户(我)必须批准访问,然后应用程序收到授权令牌,然后我可以使用它来查询用户(我的)联系人。

因为我只访问我自己的数据,有没有办法 "pre-authorize" 我自己?理想情况下,我希望能够检索一些授权令牌,然后我 运行 脚本并将该令牌作为环境变量传递

AUTH_TOKEN=12345 python my_script.py

这样就不需要用户 input/interaction 授权一次。

您描述的实现调用完整的 "three-legged" OAuth 握手,这需要明确的用户同意。如果您不需要用户同意,您可以通过 Google service account, which is tied to an application, rather than a user. Once you've granted permission to your service account to access your contacts, you can use the oauth2client ServiceAccountCredentials class 使用 "two-legged" OAuth 直接访问 GData 而无需用户同意。

这是来自 Google service account documentation 的双足身份验证示例:

import json

from httplib2 import Http

from oauth2client.service_account import ServiceAccountCredentials
from apiclient.discovery import build

scopes = ['https://www.googleapis.com/auth/sqlservice.admin']

credentials = ServiceAccountCredentials.from_json_keyfile_name(
        'service-account.json', scopes)

sqladmin = build('sqladmin', 'v1beta3', credentials=credentials)
response = sqladmin.instances().list(project='examinable-example-123').execute()

print response