מדריך למתחילים ב-Python

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

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

מטרות

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

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

  • חשבון Google.

הגדרת הסביבה

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

הפעלת ה-API

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

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

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

    לדף Clients

  2. לוחצים על Create Client (יצירת לקוח).
  3. לוחצים על Application type > Desktop app.
  4. בשדה Name, מקלידים שם לפרטי הכניסה. השם הזה מוצג רק במסוף Google Cloud.
  5. לוחצים על יצירה.

    פרטי הכניסה החדשים שנוצרו מופיעים בקטע 'מזהי לקוח OAuth 2.0'.

  6. שומרים את קובץ ה-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. בספריית העבודה, מבצעים build ומריצים את הדוגמה:

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

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

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

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

השלבים הבאים