為使用服務帳戶的客戶提供 Python 快速入門導覽課程

請按照本快速入門指南中的步驟操作,而且在大約 10 分鐘後,您會有簡單的 Python 指令列應用程式,透過服務帳戶向零接觸註冊客戶客戶要求傳送要求。

必備條件

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

  • 連結至您的零接觸註冊機制客戶帳戶的服務帳戶。請參閱開始使用
  • Python 3.0 以上版本。
  • pip 套件管理工具。
  • 連線至網際網路和網路瀏覽器。

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

  1. 使用這個精靈在 Google Developers Console 中建立或選取專案,然後自動啟用 API。依序點選「繼續」和「前往憑證」
  2. 將「您要存取哪些資料?」設為「應用程式資料」
  3. 點選「下一步」。系統會提示您建立服務帳戶。
  4. 為「服務帳戶名稱」輸入描述性名稱。
  5. 請記下服務帳戶 ID (與電子郵件地址相似),以便稍後使用。
  6. 將「角色」設為「服務帳戶」>「服務帳戶使用者」
  7. 按一下「Done」(完成),即完成建立服務帳戶。
  8. 按一下您建立的服務帳戶電子郵件地址。
  9. 按一下「金鑰」。
  10. 點選「新增金鑰」,然後點選「建立新的金鑰」。
  11. 在「金鑰類型」部分選取 [JSON]。
  12. 按一下「Create」(建立),並將私密金鑰下載到電腦上。
  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

Notes

  • 避免與他人共用 service_account_key.json 檔案。但請不要將它們加入原始碼存放區。詳情請參閱處理服務帳戶密鑰的建議做法。

瞭解詳情