Panduan memulai Python untuk pelanggan

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.

Prasyarat

Untuk menjalankan panduan memulai ini, Anda memerlukan:

  • Akun Google, yang adalah anggota pelanggan pendaftaran zero-touch Anda menggunakan akun layanan. Lihat Mendapatkan memulai.
  • Python 3.0 atau yang lebih baru.
  • Pengelolaan paket pip menyediakan alat command line gcloud.
  • 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 Go to credentials .
  2. Klik Batal di bagian Buat kredensial.
  3. Di bagian atas halaman, pilih tab OAuth consent screen. Pilih Alamat email, masukkan Nama produk jika belum ditetapkan, dan klik tombol Simpan.
  4. Pilih tab Credentials, klik Create credentials dan pilih OAuth client ID.
  5. Pilih jenis aplikasi Lainnya, masukkan nama "Panduan memulai", lalu klik tombol Buat tombol.
  6. Klik Oke untuk menutup panel Klien OAuth.
  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

Melihat penginstalan library halaman untuk penginstalan yang berbeda lainnya.

Langkah 3: Menyiapkan contoh aplikasi

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 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

Gunakan bantuan sistem operasi Anda untuk menjalankan skrip dalam file. Pada UNIX dan Mac komputer, 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 membukanya di browser Anda. Jika Anda belum {i>login<i} ke Akun Google, diminta untuk {i>log in<i}. Jika Anda login ke beberapa Akun Google, halaman akan meminta Anda memilih akun untuk otorisasi.
  2. Klik Setuju.
  3. Tutup tab browser—aplikasi terus berjalan.

Catatan

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

Pemecahan masalah

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

  • Pastikan Anda memberi otorisasi panggilan API dengan Akun Google yang sama dengan yang menjadi anggota akun pelanggan pendaftaran zero-touch. 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.

Pelajari lebih lanjut