Panduan memulai Python untuk pelanggan yang menggunakan akun layanan

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

Prasyarat

Untuk menjalankan panduan memulai ini, Anda memerlukan:

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

Langkah 1: Aktifkan API pendaftaran zero-touch

  1. Gunakan wizard ini untuk membuat atau memilih project di Google Developers Console dan otomatis mengaktifkan API. Klik Continue, lalu Go to credentials .
  2. Setel Data apa yang akan Anda akses? ke Data aplikasi.
  3. Klik Berikutnya. Anda akan diminta untuk membuat akun layanan.
  4. Beri nama deskriptif untuk Nama akun layanan.
  5. Catat ID akun layanan (formatnya 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 dibuat.
  9. Klik **Kunci**.
  10. Klik **Add key**, lalu klik **Create new key**.
  11. Untuk **Key type**, pilih **JSON**.
  12. Klik Create 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

Lihat halaman penginstalan library untuk mengetahui berbagai opsi penginstalan.

Langkah 3: Siapkan contoh file

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

#!/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 Anda

Salin service_account_key.json yang didownload saat membuat akun layanan ke dalam direktori kerja.

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

  • Jangan membagikan file service_account_key.json Anda kepada siapa pun. Berhati-hatilah untuk tidak menyertakannya dalam repositori kode sumber. Anda dapat membaca saran selengkapnya tentang menangani rahasia akun layanan.

Mempelajari lebih lanjut