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

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

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

מטרות

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

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

  • חשבון Google.

הגדרת הסביבה

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

מפעילים את ה-API

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

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

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

    כניסה לדף Clients

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

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

  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. לוחצים על Accept.

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

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

השלבים הבאים