面向客户的 Python 快速入门

按照本快速入门指南中的步骤操作,大约在 10 分钟内,您便可以获得一个向零触摸注册客户 API 发出请求的简单 Python 命令行应用。

前提条件

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

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

第 1 步:启用 Zero-Touch Enrollment API

  1. 可以使用此向导在 Google Developers Console 中创建或选择项目,并自动启用此 API。点击继续,然后点击转到凭据
  2. 点击“创建凭据”上的取消
  3. 在页面顶部,选择 OAuth 同意屏幕标签页。选择电子邮件地址,输入产品名称(如果尚未设置),然后点击保存按钮。
  4. 选择凭据标签页,点击创建凭据按钮,然后选择 OAuth 客户端 ID
  5. 选择应用类型其他,输入名称“快速入门”,然后点击创建按钮。
  6. 点击确定以关闭 OAuth 客户端面板。
  7. 点击 下载 JSON
  8. 将文件移至工作目录,并将其重命名为 client_secret.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 import tools
from oauth2client.client import flow_from_clientsecrets
from oauth2client.file import Storage

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


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

  Ask the user to authorize the request using their Google Account in their
  browser. Because this method stores the cedential in the
  USER_CREDENTIAL_FILE, the user is typically only asked to the first time they
  run the script.

  Returns:
    Credentials, the user's credential.
  """
  flow = flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
  storage = Storage(USER_CREDENTIAL_FILE)
  credential = storage.get()

  if not credential or credential.invalid:
    credential = tools.run_flow(flow, storage)  # skipping flags for brevity
  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 步:运行示例代码

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

python quickstart.py

首次运行该应用时,您需要授予访问权限:

  1. 该应用会尝试在您的默认浏览器中打开一个新的标签页。如果失败了,请从控制台中复制网址并在浏览器中打开网址。如果您尚未登录 Google 帐号,系统会提示您登录。如果您登录了多个 Google 帐号,该页面会提示您选择用于授权的帐号。
  2. 点击接受
  3. 关闭浏览器标签页 - 应用会继续运行。

备注

  • 由于 Google API 客户端库会将授权数据存储在文件系统中,因此后续启动不会提示您进行授权。
  • 如需重置应用的授权数据,请删除 user_credential.json 文件,然后重新运行应用。
  • 本快速入门中的授权流程非常适合命令行应用。如需了解如何向 Web 应用添加授权,请参阅 为 Web 服务器应用使用 OAuth 2.0

问题排查

以下是您需要检查的一些常见事项。 请 将快速入门中存在的问题告诉我们,我们将努力解决该问题。

  • 确保您授权的 API 调用与您的零触摸注册客户帐号中的成员帐号所用的 Google 帐号相同。请尝试使用同一 Google 帐号登录零触摸注册门户,以测试您的访问权限。
  • 确认相关帐号已在门户中接受最新的服务条款。请参阅 客户帐号

了解详情