המדריך למתחילים של Python

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

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

יוצרים אפליקציית שורת הפקודה ב-Python ששולחת בקשות ל-Drive Labels API.

מטרות

  • מגדירים את הסביבה.
  • מתקינים את ספריית הלקוח.
  • הגדרת הדוגמה.
  • מריצים את הדוגמה.

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

  • חשבון Google.

הגדרת הסביבה

כדי להשלים את המדריך למתחילים הזה, עליכם להגדיר את הסביבה.

הפעלת ה-API

לפני שמשתמשים ב-Google APIs, צריך להפעיל אותם בפרויקט ב-Google Cloud. אפשר להפעיל ממשק API אחד או יותר בפרויקט אחד ב-Google Cloud.

אישור פרטי כניסה לאפליקציה בשולחן העבודה

כדי לאמת משתמשי קצה ולגשת לנתוני משתמשים באפליקציה, צריך ליצור מזהה לקוח אחד או יותר ב-OAuth 2.0. מזהה לקוח משמש לזיהוי של אפליקציה יחידה בשרתי ה-OAuth של Google. אם האפליקציה פועלת בכמה פלטפורמות, צריך ליצור מזהה לקוח נפרד לכל פלטפורמה.
  1. במסוף Google Cloud, נכנסים לתפריט > APIs & Services > Credentials.

    כניסה לדף Credentials

  2. לוחצים על Create Credentials > OAuth client ID.
  3. לוחצים על סוג אפליקציה > אפליקציית מחשב.
  4. בשדה Name, מקלידים שם לפרטי הכניסה. השם הזה מוצג רק במסוף Google Cloud.
  5. לוחצים על יצירה. יופיע המסך שנוצר על ידי לקוח OAuth ומוצג בו מזהה הלקוח החדש וסוד הלקוח שלכם.
  6. לוחצים על אישור. פרטי הכניסה החדשים שנוצרו יופיעו בקטע מזהי לקוח OAuth 2.0.
  7. שומרים את קובץ ה-JSON שהורדתם בתור credentials.json ומעבירים את הקובץ לספריית העבודה.

התקנת ספריית הלקוח של Google

  • מתקינים את ספריית הלקוח של Google ל-Python:

      pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib
    

אפשרויות התקנה חלופיות מפורטות בקטע 'התקנה' בספריית Python.

הגדרת הדוגמה

  1. בספריית העבודה, יוצרים קובץ בשם quickstart.py.
  2. צריך לכלול את הקוד הבא ב-quickstart.py:

    import os.path
    
    from google.auth.transport.requests import Request
    from google.oauth2.credentials import Credentials
    from google_auth_oauthlib.flow import InstalledAppFlow
    from googleapiclient.discovery import build
    from googleapiclient.errors import HttpError
    
    # If modifying these scopes, delete the file token.json.
    SCOPES = ['https://www.googleapis.com/auth/drive.labels.readonly']
    
    def main():
      """Shows basic usage of the Drive Labels API.
    
        Prints the first page of the customer's Labels.
      """
      creds = None
      # The file token.json stores the user's access and refresh tokens, and is
      # created automatically when the authorization flow completes for the first
      # time.
      if os.path.exists('token.json'):
        creds = Credentials.from_authorized_user_file('token.json', SCOPES)
      # If there are no (valid) credentials available, let the user log in.
      if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
          creds.refresh(Request())
        else:
          flow = InstalledAppFlow.from_client_secrets_file('credentials.json',
                                                          SCOPES)
          creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open('token.json', 'w') as token:
          token.write(creds.to_json())
      try:
        service = build('drivelabels', 'v2', credentials=creds)
        response = service.labels().list(
            view='LABEL_VIEW_FULL').execute()
        labels = response['labels']
    
        if not labels:
          print('No Labels')
        else:
          for label in labels:
            name = label['name']
            title = label['properties']['title']
            print(u'{0}:\t{1}'.format(name, title))
      except HttpError as error:
        # TODO (developer) - Handle errors from Labels API.
        print(f'An error occurred: {error}')
    
    if __name__ == '__main__':
      main()
    

הרצת הדוגמה

  1. בספריית העבודה, יוצרים ומריצים את הדוגמה:

    python quickstart.py
    
  2. בפעם הראשונה שמריצים את הדוגמה, מוצגת בקשה לאשר גישה:

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

    פרטי ההרשאות נשמרים במערכת הקבצים, ולכן בפעם הבאה שמריצים את הקוד לדוגמה לא תוצג לכם בקשה להרשאה.

יצרתם בהצלחה את אפליקציית Python הראשונה שלכם ששולחת בקשות ל-Drive Labels API.

השלבים הבאים