面向客户的 Python 快速入门

按照本快速入门指南中的步骤操作,在大约 10 分钟内 简单的 Python 命令行应用程序,用于向零触摸 注册客户 API。

前提条件

如需运行本快速入门,您需要:

  • Google 账号(属于您的零触摸注册客户的成员) 。请参阅获取 开始
  • Python 3.0 或更高版本。
  • pip 软件包管理 工具。
  • 能够访问互联网和网络浏览器。

第 1 步:启用零触摸注册 API

  1. 使用此 向导,以在 Google Developers Console 中创建或选择项目。 系统会自动启用该 API。点击继续,然后点击前往凭据页面
  2. 在“创建凭据”页面上点击取消
  3. 在页面顶部,选择 OAuth 同意屏幕标签页。请选择一个 Email address(电子邮件地址),输入 Product name(如果尚未设置),并且 点击保存按钮。
  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 文件,然后再次运行应用。
  • 本快速入门中的授权流程非常适合命令行应用。如需了解如何添加 授权,请参阅 针对网络服务器应用使用 OAuth 2.0

问题排查

以下是您需要检查的一些常见事项。 <ph type="x-smartling-placeholder"></ph> 请将快速入门中的问题告诉我们,我们将努力解决此问题。

  • 确保您在授权 API 调用时使用的 Google 账号是您 零触摸注册客户账号。尝试使用以下网址登录零触摸注册门户: 请使用同一个 Google 账号测试您的访问权限。
  • 确认账号已接受最新版《服务条款》 门户网站。请参阅 客户账号

了解详情