お客様向け Python クイックスタート

このクイックスタート ガイドの手順に沿って操作すると、ゼロタッチ登録のカスタマー API にリクエストを送信するシンプルな Python コマンドライン アプリが約 10 分で作成できます。

前提条件

このクイックスタートを実行するには、次のものが必要です。

  • ゼロタッチ登録のお客様のアカウントのメンバーである Google アカウント。詳しくは、 開始されました
  • Python 3.0 以降。
  • pip パッケージ管理ツール。
  • インターネット アクセスとウェブブラウザ。

ステップ 1: ゼロタッチ登録 API を有効にする

  1. Google Developers Console でこちらのウィザードを使ってプロジェクトを作成するか既存のプロジェクトを選択すると、自動的に API が有効になります。[続行] をクリックし、[認証情報に進む] をクリックします。
  2. [認証情報の作成] で [キャンセル] をクリックします。
  3. ページ上部の [OAuth 同意画面] タブを選択します。メールアドレスを選択し、[ユーザーに表示するサービス名] が設定されていない場合はサービス名を入力して、[保存] ボタンをクリックします。
  4. [認証情報] タブを選択し、[認証情報を作成] ボタンをクリックして、[OAuth クライアント ID] を選択します。
  5. アプリケーション タイプとして [その他] を選択し、名前を入力します。 [クイックスタート] を選択し、[Create] をクリックします。 ] ボタンを離します。
  6. [OK] をクリックして [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. [Accept] をクリックします。
  3. ブラウザタブを閉じてもアプリは実行を継続します。

メモ

  • Google API クライアント ライブラリは承認データをファイル システムに保存するため、その後の起動時に承認を求めるメッセージは表示されません。
  • アプリの認証データをリセットするには、 user_credential.json ファイルを実行し、アプリを再度実行します。
  • このクイックスタートの承認フローは、コマンドライン アプリに最適です。Google Chat で 認証については、をご覧ください。 ウェブサーバー アプリケーションに OAuth 2.0 を使用する

トラブルシューティング

確認する必要がある一般的な事項は次のとおりです。 クイックスタートの問題点をお聞かせください。修正いたします。

  • ゼロタッチ登録のお客様アカウントのメンバーである同じ Google アカウントで API 呼び出しを承認していることを確認します。以下を使用してゼロタッチ登録ポータルにログインしてみてください。 同じ Google アカウントを使ってアクセスをテストします。
  • アカウントがポータルで最新の利用規約に同意していることを確認します。顧客アカウントをご覧ください。

その他の情報