客戶的 Python 快速入門導覽課程

請按照這份快速入門指南中的步驟進行,大約 10 分鐘後開始 簡單的 Python 指令列應用程式,向零接觸 用於註冊客戶 API

必要條件

如要執行本快速入門導覽課程,您需要:

  • 擁有零接觸註冊機制客戶的 Google 帳戶 讓他們使用服務帳戶請參閱取得 已開始
  • Python 3.0 以上版本。
  • pip 套件管理 如果偏好在終端機視窗中工作 可使用 Google Cloud CLI gcloud 指令列工具
  • 連上網際網路和網路瀏覽器。

步驟 1:啟用零接觸註冊機制 API

  1. 請使用此 精靈在 Google Developers Console 中建立或選取專案,並且 系統會自動啟用 API依序點選「繼續」和「前往憑證」
  2. 按一下「建立憑證」上的「取消」
  3. 選取頁面頂端的「OAuth 同意畫面」分頁標籤。選取 Email address (電子郵件地址),輸入產品名稱 (如果尚未設定) 按一下「儲存」按鈕。
  4. 選取「Credentials」分頁標籤,然後按一下「Create credentials」 按鈕,然後選取「OAuth 用戶端 ID」
  5. 選取應用程式類型 Other,然後輸入名稱 「快速入門導覽課程」,然後按一下「建立」 按鈕。
  6. 按一下「OK」,關閉「OAuth 用戶端」面板。
  7. 按一下「Download JSON」(下載 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. 然後點選 [Accept]
  3. 關閉瀏覽器分頁,應用程式會繼續執行。

附註

  • 由於 Google API 用戶端程式庫會在檔案系統中儲存授權資料,因此 就不會提示您授權
  • 如要重設應用程式的授權資料,請刪除應用程式的 user_credential.json 檔案,然後再次執行應用程式。
  • 本快速入門導覽課程的授權流程非常適合用於指令列應用程式。瞭解如何 授權網頁應用程式,請參閱 針對網路伺服器應用程式使用 OAuth 2.0

疑難排解

以下是部分需要檢查的常見事項。 只要在快速入門導覽課程中告訴我們問題所在,我們就會加以修正。

  • 請確認您用來授權 API 呼叫的 Google 帳戶隸屬於 零接觸註冊機制客戶帳戶。嘗試登入零接觸註冊機制入口網站, 以便測試存取情形
  • 確認以下位置的帳戶已接受最新的《服務條款》: 入口網站。詳情請參閱 客戶帳戶

瞭解詳情