Panduan memulai Python untuk pelanggan

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.

Prasyarat

Untuk menjalankan panduan memulai ini, Anda memerlukan:

  • Akun Google, yang merupakan anggota 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. Klik Batal di bagian Buat kredensial.
  3. Di bagian atas halaman, pilih tab Layar izin OAuth. Pilih Alamat email, masukkan Nama produk jika belum ditetapkan, lalu klik tombol Simpan.
  4. Pilih tab Credentials, klik tombol Create credentials, lalu pilih OAuth client ID.
  5. Pilih jenis aplikasi Other, masukkan nama "Quickstart", lalu klik tombol Create.
  6. Klik OK untuk menutup panel OAuth client.
  7. Klik Download JSON.
  8. Pindahkan file ke direktori kerja Anda dan ganti namanya menjadi client_secret.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 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()

Langkah 4: Jalankan contoh aplikasi

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

Saat pertama kali menjalankan aplikasi, Anda perlu mengizinkan akses:

  1. Aplikasi akan mencoba membuka tab baru di browser default Anda. Jika gagal, salin URL dari konsol dan buka di browser. Jika belum login ke Akun Google, Anda akan diminta untuk login. Jika Anda login ke beberapa Akun Google, halaman tersebut akan meminta Anda memilih akun untuk otorisasi.
  2. Klik Accept.
  3. Tutup tab browser—aplikasi akan terus berjalan.

Catatan

  • Karena library klien Google API menyimpan data otorisasi di sistem file, peluncuran berikutnya tidak akan meminta Anda melakukan otorisasi.
  • Untuk mereset data otorisasi aplikasi, hapus file user_credential.json dan jalankan kembali aplikasi.
  • Alur otorisasi di panduan memulai ini ideal untuk aplikasi command line. Untuk mempelajari cara menambahkan otorisasi ke aplikasi web, lihat Menggunakan OAuth 2.0 untuk Aplikasi Server Web.

Pemecahan masalah

Berikut adalah beberapa hal umum yang sebaiknya Anda periksa. Beri tahu kami apa yang salah dengan panduan memulai dan kami akan berupaya memperbaikinya.

  • Pastikan Anda mengizinkan panggilan API dengan Akun Google yang sama dengan yang menjadi anggota akun pelanggan pendaftaran zero-touch Anda. Coba login ke portal pendaftaran zero-touch menggunakan Akun Google yang sama untuk menguji akses Anda.
  • Konfirmasi bahwa akun telah menyetujui Persyaratan Layanan terbaru di portal. Lihat Akun pelanggan.

Mempelajari lebih lanjut