Panduan memulai Python untuk pelanggan yang menggunakan akun layanan

Ikuti langkah-langkah dalam panduan memulai ini, dan dalam waktu sekitar 10 menit Anda sudah aplikasi command line Python sederhana yang membuat permintaan ke zero-touch API pelanggan pendaftaran menggunakan akun layanan.

Prasyarat

Untuk menjalankan panduan memulai ini, Anda memerlukan:

  • Akun layanan, yang ditautkan ke akun pelanggan pendaftaran zero-touch Anda. Lihat Mendapatkan memulai.
  • Python 3.0 atau yang lebih baru.
  • Alat pengelolaan paket pip.
  • Akses ke internet dan browser web.

Langkah 1: Aktifkan API pendaftaran zero-touch

  1. Gunakan ini wizard untuk membuat atau memilih project di Google Developers Console dan mengaktifkan API secara otomatis. Klik Lanjutkan, lalu Buka kredensial.
  2. Setel Data apa yang akan Anda akses? ke Data aplikasi.
  3. Klik Berikutnya. Anda akan diminta untuk membuat layanan menggunakan akun layanan.
  4. Beri nama deskriptif untuk Nama akun layanan.
  5. Catat ID akun layanan (terlihat seperti alamat email) karena Anda akan menggunakannya nanti.
  6. Tetapkan Role ke Service Accounts > Service Account User.
  7. Klik Selesai untuk menyelesaikan pembuatan akun layanan.
  8. Klik alamat email untuk akun layanan yang Anda buat.
  9. Klik **Keys**.
  10. Klik **Add key**, kemudian klik **Create new key**.
  11. Untuk **Key type**, pilih **JSON**.
  12. Klik Buat dan kunci pribadi akan didownload ke komputer Anda.
  13. Klik **Tutup**.
  14. Pindahkan file ke direktori kerja Anda dan ganti namanya menjadi service_account_key.json.

Langkah 2: Instal library klien Google

Jalankan perintah berikut untuk menginstal library menggunakan pip:

pip install --upgrade google-api-python-client oauth2client

Melihat penginstalan library halaman untuk penginstalan yang berbeda lainnya.

Langkah 3: Siapkan contoh

Buat file bernama quickstart.py di direktori kerja Anda. Salin di kode berikut dan simpan filenya.

#!/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()

Langkah 4: Tambahkan kunci akun layanan

Salin service_account_key.json yang Anda download saat membuat akun layanan ke direktori kerja Anda.

Langkah 5: Jalankan contoh

Gunakan bantuan sistem operasi untuk menjalankan skrip dalam file. Di komputer UNIX dan Mac, jalankan perintah di bawah ini di terminal Anda:

python quickstart.py

Catatan

  • Hindari membagikan file service_account_key.json Anda kepada siapa pun. Hati-hati jangan memasukkannya ke dalam repositori kode sumber. Anda dapat membaca saran selengkapnya tentang menangani secret akun layanan.

Pelajari lebih lanjut