מדריך למתחילים בנושא Python ללקוחות

פועלים לפי השלבים במדריך למתחילים. אחרי כ-10 דקות, אפליקציית שורת פקודה פשוטה ב-Python ששולחת בקשות דרך הארגון ממשק ה-API של רישום לקוח.

דרישות מוקדמות

כדי להפעיל את המדריך למתחילים הזה, צריך:

  • חשבון Google שחבר בלקוח שלכם בהרשמה דרך הארגון חשבון. למידע נוסף בתהליך.
  • Python בגרסה 3.0 ומעלה.
  • ניהול החבילות pip של Google.
  • גישה לאינטרנט ולדפדפן אינטרנט.

שלב 1: מפעילים את ה-API להרשמה דרך הארגון

  1. אפשר להשתמש בקישור הזה באשף ליצירה או בחירה של פרויקט ב-Google Developers Console, להפעיל את ה-API באופן אוטומטי. לוחצים על המשך ואז על מעבר לפרטי הכניסה. .
  2. לוחצים על Cancel (ביטול) בדף Create Credentials.
  3. בחלק העליון של הדף, לוחצים על הכרטיסייה OAuth screen consent (מסך ההסכמה של OAuth). בוחרים את כתובת אימייל, מזינים את שם המוצר (אם הוא עדיין לא מוגדר). לוחצים על הלחצן שמירה.
  4. בוחרים בכרטיסייה Credentials ואז לוחצים על Create credentials. ובוחרים באפשרות OAuth Client ID (מזהה לקוח OAuth).
  5. בוחרים את סוג האפליקציה אחר ומזינים את שם האפליקציה 'מדריך למתחילים', ולוחצים על יצירה. לחצן.
  6. לוחצים על OK כדי לסגור את החלונית לקוח OAuth.
  7. לוחצים על הורדת JSON.
  8. צריך להעביר את הקובץ לספריית העבודה ולשנות את השם שלו ל-client_secret.json.

שלב 2: מתקינים את ספריית הלקוח של Google

מריצים את הפקודה הבאה כדי להתקין את הספרייה באמצעות PIP:

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

לצפייה בהתקנה של הספרייה דף שונות להתקנה אפשרויות.

שלב 3: הגדרת הדוגמה

יוצרים קובץ בשם quickstart.py בספריית העבודה. מעתיקים את את הקוד הבא ושומרים את הקובץ.

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

שלב 4: הרצת הדוגמה

מריצים את הסקריפט שבקובץ בעזרת העזרה של מערכת ההפעלה. ב-UNIX וב-Mac מריצים את הפקודה הבאה בטרמינל:

python quickstart.py

בפעם הראשונה שמפעילים את האפליקציה, צריך לתת הרשאה לגישה:

  1. האפליקציה תנסה לפתוח כרטיסייה חדשה בדפדפן ברירת המחדל. אם הפעולה נכשלת, מעתיקים את כתובת ה-URL במסוף ופותחים אותו בדפדפן. אם עדיין לא התחברתם לחשבון Google, סימן צריך להתחבר לחשבון. אם אתם מחוברים לכמה חשבונות Google, בדף תתבקשו לבחור חשבון עבור ההרשאה.
  2. לוחצים על אישור.
  3. סוגרים את הכרטיסייה בדפדפן – האפליקציה ממשיכה לפעול.

הערות

  • מכיוון שספריית הלקוח של Google API מאחסנת נתוני הרשאות במערכת הקבצים, הפעלות לא יבקשו ממך הרשאה.
  • כדי לאפס את נתוני ההרשאות של האפליקציה, מוחקים את user_credential.json ולהפעיל שוב את האפליקציה.
  • תהליך ההרשאה במדריך למתחילים הזה אידיאלי לאפליקציית שורת הפקודה. הוראות להוספה הרשאה לאפליקציית אינטרנט: שימוש ב-OAuth 2.0 לאפליקציות של שרת אינטרנט

פתרון בעיות

הנה כמה דברים נפוצים שכדאי לבדוק. אפשר לספר לנו מה השתבש במדריך למתחילים, וננסה לפתור את הבעיה.

  • צריך לוודא שאתם מאשרים קריאות ל-API דרך אותו חשבון Google שהוא חבר ב- חשבון לקוח בהרשמה דרך הארגון. כדאי לנסות להיכנס לפורטל ההרשמה דרך הארגון באמצעות באותו חשבון Google כדי לבדוק את הגישה.
  • לאשר שהחשבון אישר את התנאים וההגבלות העדכניים של הפורטל. ראו חשבונות לקוח.

מידע נוסף