Hướng dẫn bắt đầu nhanh cho Python cho khách hàng sử dụng tài khoản dịch vụ

Làm theo các bước trong hướng dẫn bắt đầu nhanh này. Trong khoảng 10 phút, bạn có một ứng dụng dòng lệnh Python đơn giản giúp thực hiện các yêu cầu đối với API khách hàng thiết lập tự động bằng tài khoản dịch vụ.

Điều kiện tiên quyết

Để chạy tính năng khởi động nhanh này, bạn cần:

  • Một tài khoản dịch vụ được liên kết với tài khoản khách hàng thiết lập tự động. Xem phần Bắt đầu.
  • Python.
  • Công cụ quản lý gói pip.
  • Truy cập Internet và trình duyệt web.

Bước 1: Bật API thiết lập tự động

  1. Sử dụng trình hướng dẫn này để tạo hoặc chọn một dự án trong Google Developers Console và tự động bật API. Nhấp vào Tiếp tục, sau đó nhấp vào Chuyển đến thông tin đăng nhập.
  2. Đặt Bạn sẽ truy cập dữ liệu nào? thành Dữ liệu ứng dụng.
  3. Nhấp vào Tiếp theo. Bạn sẽ được nhắc tạo một tài khoản dịch vụ.
  4. Đặt tên mô tả cho Tên tài khoản dịch vụ.
  5. Hãy lưu ý đến Mã tài khoản dịch vụ (có vẻ giống như địa chỉ email) vì bạn sẽ sử dụng thông tin này sau.
  6. Đặt Vai trò thành Tài khoản dịch vụ > Người dùng tài khoản dịch vụ.
  7. Nhấp vào Xong để hoàn tất việc tạo tài khoản dịch vụ.
  8. Nhấp vào địa chỉ email cho tài khoản dịch vụ mà bạn đã tạo.
  9. Nhấp vào **Khóa**.
  10. Nhấp vào **Thêm khoá**, sau đó nhấp vào **Tạo khoá mới**.
  11. Đối với **Loại khóa**, hãy chọn **JSON**.
  12. Nhấp vào Tạo và khóa cá nhân sẽ được tải xuống máy tính của bạn.
  13. Nhấp vào **Đóng**.
  14. Di chuyển tệp vào thư mục đang làm việc và đổi tên service_account_key.json.

Bước 2: Cài đặt thư viện ứng dụng Google

Chạy lệnh sau để cài đặt thư viện bằng pip:

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

Hãy xem trang cài đặt của thư viện để biết các tuỳ chọn cài đặt khác nhau.

Bước 3: Thiết lập mẫu

Tạo tệp có tên quickstart.py trong thư mục đang làm việc của bạn. Sao chép mã sau đây và lưu tệp.

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

Bước 4: Thêm khóa tài khoản dịch vụ của bạn

Sao chép service_account_key.json mà bạn đã tải xuống khi tạo tài khoản dịch vụ vào thư mục đang làm việc.

Bước 5: Chạy mẫu

Sử dụng trợ giúp của hệ điều hành để chạy tập lệnh trong tệp. Trên máy tính UNIX và Mac, hãy chạy lệnh bên dưới trong thiết bị đầu cuối của bạn:

python quickstart.py

Ghi chú

Tìm hiểu thêm