经过一番挖掘,我发现了几个基于 OAuth2 身份验证的示例。由此,我制作了以下简单示例,该示例创建了一个 JWT 来访问日历 API:
import httplib2
import pprint
from apiclient.discovery import build
from oauth2client.client import SignedJwtAssertionCredentials
# Get the private key from the Google supplied private key file.
f = file("your_private_key_file.p12", "rb")
key = f.read()
f.close()
# Create the JWT
credentials = SignedJwtAssertionCredentials(
"xxxxxxxxxx@developer.gserviceaccount.com", key,
scope="https://www.googleapis.com/auth/calendar"
)
# Create an authorized http instance
http = httplib2.Http()
http = credentials.authorize(http)
# Create a service call to the calendar API
service = build("calendar", "v3", http=http)
# List all calendars.
lists = service.calendarList().list(pageToken=None).execute(http=http)
pprint.pprint(lists)
要在 Google App Engine 上工作,您需要为您的应用启用 PyCrypto。这意味着将以下内容添加到您的app.yaml
文件中:
libraries:
- name: pycrypto
version: "latest"