面向使用服务帐号的客户的 Python 快速入门

按照本快速入门指南中的步骤操作,大约 10 分钟后,您就有了一个简单的 Python 命令行应用,该应用使用服务帐号向零触摸注册客户 API 发出请求。

前提条件

如需运行本快速入门,您需要执行以下操作:

  • 关联到您的零触摸注册客户帐号的服务帐号。请参阅使用入门
  • Python 3.0 或更高版本。
  • pip 软件包管理工具。
  • 能够访问互联网和网络浏览器。

第 1 步:启用 Zero-Touch Enrollment API

  1. 可以使用此向导在 Google Developers Console 中创建或选择项目,并自动启用此 API。点击继续,然后点击转到凭据
  2. 您要访问哪些数据?设为应用数据
  3. 点击 Next。系统会提示您创建服务帐号。
  4. 服务帐号名称指定一个描述性名称。
  5. 记下服务帐号 ID(类似于电子邮件地址),因为您稍后会用到它。
  6. 角色设置为服务帐号 > Service Account User
  7. 点击完成以完成服务帐号的创建过程。
  8. 点击您创建的服务帐号的电子邮件地址。
  9. 点击 **密钥**。
  10. 点击 **添加密钥**,然后点击 **创建新密钥**。
  11. 对于 **密钥类型**,选择 **JSON**。
  12. 点击创建,私钥即会下载到您的计算机。
  13. 点击 **关闭**。
  14. 将文件移至工作目录,并将其重命名为 service_account_key.json

第 2 步:安装 Google 客户端库

运行以下命令,使用 pip 安装该库:

pip install --upgrade google-api-python-client oauth2client

如需了解不同的安装选项,请参阅库的安装页面

第 3 步:设置示例

在工作目录中创建名为 quickstart.py 的文件。复制以下代码并保存文件。

#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Zero-touch enrollment quickstart sample.

This script forms the quickstart introduction to the zero-touch enrollemnt
customer API. To learn more, visit https://developer.google.com/zero-touch
"""

import sys
from apiclient import discovery
import httplib2
from oauth2client.service_account import ServiceAccountCredentials

# A single auth scope is used for the zero-touch enrollment customer API.
SCOPES = ['https://www.googleapis.com/auth/androidworkzerotouchemm']
SERVICE_ACCOUNT_KEY_FILE = 'service_account_key.json'


def get_credential():
  """Creates a Credential object with the correct OAuth2 authorization.

  Uses the service account key stored in SERVICE_ACCOUNT_KEY_FILE.

  Returns:
    Credentials, the user's credential.
  """
  credential = ServiceAccountCredentials.from_json_keyfile_name(
    SERVICE_ACCOUNT_KEY_FILE, SCOPES)

  if not credential or credential.invalid:
    print('Unable to authenticate using service account key.')
    sys.exit()
  return credential


def get_service():
  """Creates a service endpoint for the zero-touch enrollment API.

  Builds and returns an authorized API client service for v1 of the API. Use
  the service endpoint to call the API methods.

  Returns:
    A service Resource object with methods for interacting with the service.
  """
  http_auth = get_credential().authorize(httplib2.Http())
  return discovery.build('androiddeviceprovisioning', 'v1', http=http_auth)


def main():
  """Runs the zero-touch enrollment quickstart app.
  """
  # Create a zero-touch enrollment API service endpoint.
  service = get_service()

  # Get the customer's account. Because a customer might have more
  # than one, limit the results to the first account found.
  response = service.customers().list(pageSize=1).execute()

  if 'customers' not in response:
    # No accounts found for the user. Confirm the Google Account
    # that authorizes the request can access the zero-touch portal.
    print('No zero-touch enrollment account found.')
    sys.exit()
  customer_account = response['customers'][0]['name']

  # Send an API request to list all the DPCs available using the customer
  # account.
  results = service.customers().dpcs().list(parent=customer_account).execute()

  # Print out the details of each DPC.
  for dpc in results['dpcs']:
    # Some DPCs may not have a name, so replace with a marker.
    if 'dpcName' in dpc:
      dpcName = dpc['dpcName']
    else:
      dpcName = "-"
    print('Name:{0}  APK:{1}'.format(dpcName, dpc['packageName']))


if __name__ == '__main__':
  main()

第 4 步:添加服务帐号密钥

将您创建服务帐号时下载的 service_account_key.json 复制到工作目录中。

第 5 步:运行示例

请使用操作系统的帮助来运行该文件中的脚本。在 UNIX 和 Mac 计算机上,在终端中运行以下命令:

python quickstart.py

备注

  • 避免与任何人共享您的 service_account_key.json 文件。请注意不要将其包含在源代码库中。您可以详细了解如何处理服务帐号密钥

了解详情