คู่มือเริ่มต้นใช้งาน Python

บทแนะนำแบบย่อจะอธิบายวิธีตั้งค่าและเรียกใช้แอปที่เรียกใช้ Google Workspace API

เครื่องมือเริ่มต้นใช้งาน Google Workspace ใช้ไลบรารีของไคลเอ็นต์ API เพื่อจัดการรายละเอียดบางอย่างของขั้นตอนการตรวจสอบสิทธิ์และการให้สิทธิ์ เราขอแนะนําให้คุณใช้คลังไลบรารีไคลเอ็นต์สําหรับแอปของคุณเอง คู่มือเริ่มต้นฉบับย่อนี้ใช้แนวทางการตรวจสอบสิทธิ์แบบง่ายที่เหมาะกับสภาพแวดล้อมการทดสอบ สําหรับสภาพแวดล้อมเวอร์ชันที่ใช้งานจริง เราขอแนะนําให้ดูข้อมูลเกี่ยวกับการตรวจสอบสิทธิ์และการให้สิทธิ์ก่อนเลือกข้อมูลเข้าสู่ระบบที่เหมาะสมสําหรับแอป

สร้างแอปพลิเคชันบรรทัดคำสั่ง Python ที่ส่งคำขอไปยัง Activity API ของ Google ไดรฟ์

วัตถุประสงค์

  • ตั้งค่าสภาพแวดล้อม
  • ติดตั้งไลบรารีของไคลเอ็นต์
  • ตั้งค่าตัวอย่าง
  • เรียกใช้ตัวอย่าง

ข้อกำหนดเบื้องต้น

หากต้องการเรียกใช้การเริ่มต้นใช้งานอย่างรวดเร็วนี้ คุณต้องมีข้อกําหนดเบื้องต้นต่อไปนี้

  • บัญชี Google

ตั้งค่าสภาพแวดล้อม

ตั้งค่าสภาพแวดล้อมเพื่อเริ่มต้นใช้งานนี้ให้เสร็จสมบูรณ์

เปิดใช้ API

คุณต้องเปิดใช้ API ของ Google ในโปรเจ็กต์ Google Cloud ก่อนจึงจะใช้ได้ คุณเปิด API อย่างน้อย 1 รายการในโปรเจ็กต์ Google Cloud โปรเจ็กต์เดียวได้

หากคุณใช้โปรเจ็กต์ Google Cloud ใหม่เพื่อเริ่มต้นใช้งานด่วนนี้ ให้กําหนดค่าหน้าจอขอความยินยอม OAuth หากคุณทำขั้นตอนนี้ในโปรเจ็กต์ที่อยู่ในระบบคลาวด์เรียบร้อยแล้ว ให้ข้ามไปยังส่วนถัดไป

  1. ในคอนโซล Google Cloud ให้ไปที่เมนู > > การสร้างแบรนด์

    ไปที่การสร้างแบรนด์

  2. หากกําหนดค่า แล้ว คุณจะกําหนดการตั้งค่าหน้าจอขอความยินยอม OAuth ต่อไปนี้ได้ในการสร้างแบรนด์ กลุ่มเป้าหมาย และการเข้าถึงข้อมูล หากเห็นข้อความว่า not configured yet ให้คลิกเริ่มต้นใช้งาน
    1. ในส่วนข้อมูลแอป ให้ป้อนชื่อแอปในส่วนชื่อแอป
    2. ในอีเมลสนับสนุนสำหรับผู้ใช้ ให้เลือกอีเมลทีมสนับสนุนที่ผู้ใช้สามารถติดต่อคุณได้หากมีข้อสงสัยเกี่ยวกับการยินยอม
    3. คลิกถัดไป
    4. เลือกภายในในส่วนผู้ชม
    5. คลิกถัดไป
    6. ในส่วนข้อมูลติดต่อ ให้ป้อนอีเมลที่คุณจะใช้รับการแจ้งเตือนเกี่ยวกับการเปลี่ยนแปลงในโปรเจ็กต์
    7. คลิกถัดไป
    8. ในส่วนเสร็จสิ้น ให้อ่านนโยบายข้อมูลผู้ใช้ของบริการ Google API และเลือกฉันยอมรับนโยบายข้อมูลผู้ใช้ของบริการ Google API หากยอมรับ
    9. คลิกต่อไป
    10. คลิกสร้าง
  3. ในระหว่างนี้ คุณสามารถข้ามการเพิ่มขอบเขตได้ ในอนาคต เมื่อคุณสร้างแอปเพื่อใช้งานนอกองค์กร Google Workspace คุณต้องเปลี่ยนประเภทผู้ใช้เป็นภายนอก จากนั้นเพิ่มขอบเขตการให้สิทธิ์ที่แอปของคุณต้องใช้ ดูข้อมูลเพิ่มเติมได้ที่คู่มือกำหนดค่าความยินยอม OAuth ฉบับเต็ม

ให้สิทธิ์ข้อมูลเข้าสู่ระบบสําหรับแอปพลิเคชันบนเดสก์ท็อป

หากต้องการตรวจสอบสิทธิ์ผู้ใช้ปลายทางและเข้าถึงข้อมูลผู้ใช้ในแอป คุณต้องสร้างรหัสไคลเอ็นต์ OAuth 2.0 อย่างน้อย 1 รายการ รหัสไคลเอ็นต์ใช้เพื่อระบุแอปเดี่ยวไปยังเซิร์ฟเวอร์ OAuth ของ Google หากแอปทำงานบนหลายแพลตฟอร์ม คุณจะต้องสร้างรหัสไคลเอ็นต์แยกต่างหากสำหรับแต่ละแพลตฟอร์ม
  1. ในคอนโซล Google Cloud ให้ไปที่เมนู > > ไคลเอ็นต์

    ไปที่ลูกค้า

  2. คลิกสร้างไคลเอ็นต์
  3. คลิกประเภทแอปพลิเคชัน > แอปเดสก์ท็อป
  4. พิมพ์ชื่อของข้อมูลเข้าสู่ระบบในช่องชื่อ ชื่อนี้จะแสดงในคอนโซล 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
    

กำหนดค่าตัวอย่าง

  1. สร้างไฟล์ชื่อ quickstart.py ในไดเรกทอรีทํางาน
  2. ใส่รหัสต่อไปนี้ใน quickstart.py

    drive/activity-v2/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.activity.readonly"]
    
    
    def main():
      """Shows basic usage of the Drive Activity API.
    
      Prints information about the last 10 events that occured the user's Drive.
      """
      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())
    
      service = build("driveactivity", "v2", credentials=creds)
    
      # Call the Drive Activity API
      try:
        results = service.activity().query(body={"pageSize": 10}).execute()
        activities = results.get("activities", [])
    
        if not activities:
          print("No activity.")
        else:
          print("Recent activity:")
          for activity in activities:
            time = getTimeInfo(activity)
            action = getActionInfo(activity["primaryActionDetail"])
            actors = map(getActorInfo, activity["actors"])
            targets = map(getTargetInfo, activity["targets"])
            actors_str, targets_str = "", ""
            actor_name = actors_str.join(actors)
            target_name = targets_str.join(targets)
    
            # Print the action occurred on drive with actor, target item and timestamp
            print(f"{time}: {action}, {actor_name}, {target_name}")
    
      except HttpError as error:
        # TODO(developer) - Handleerrors from drive activity API.
        print(f"An error occurred: {error}")
    
    
    # Returns the name of a set property in an object, or else "unknown".
    def getOneOf(obj):
      for key in obj:
        return key
      return "unknown"
    
    
    # Returns a time associated with an activity.
    def getTimeInfo(activity):
      if "timestamp" in activity:
        return activity["timestamp"]
      if "timeRange" in activity:
        return activity["timeRange"]["endTime"]
      return "unknown"
    
    
    # Returns the type of action.
    def getActionInfo(actionDetail):
      return getOneOf(actionDetail)
    
    
    # Returns user information, or the type of user if not a known user.
    def getUserInfo(user):
      if "knownUser" in user:
        knownUser = user["knownUser"]
        isMe = knownUser.get("isCurrentUser", False)
        return "people/me" if isMe else knownUser["personName"]
      return getOneOf(user)
    
    
    # Returns actor information, or the type of actor if not a user.
    def getActorInfo(actor):
      if "user" in actor:
        return getUserInfo(actor["user"])
      return getOneOf(actor)
    
    
    # Returns the type of a target and an associated title.
    def getTargetInfo(target):
      if "driveItem" in target:
        title = target["driveItem"].get("title", "unknown")
        return f'driveItem:"{title}"'
      if "drive" in target:
        title = target["drive"].get("title", "unknown")
        return f'drive:"{title}"'
      if "fileComment" in target:
        parent = target["fileComment"].get("parent", {})
        title = parent.get("title", "unknown")
        return f'fileComment:"{title}"'
      return f"{getOneOf(target)}:unknown"
    
    
    if __name__ == "__main__":
      main()

เรียกใช้ตัวอย่าง

  1. ในไดเรกทอรีทํางาน ให้สร้างและเรียกใช้ตัวอย่าง ดังนี้

    python3 quickstart.py
    
  1. เมื่อเรียกใช้ตัวอย่างเป็นครั้งแรก ระบบจะแจ้งให้คุณให้สิทธิ์เข้าถึง โดยทำดังนี้
    1. หากยังไม่ได้ลงชื่อเข้าใช้บัญชี Google ให้ลงชื่อเข้าใช้เมื่อได้รับข้อความแจ้ง หากคุณลงชื่อเข้าใช้หลายบัญชี ให้เลือกบัญชีเดียวที่จะใช้สำหรับการให้สิทธิ์
    2. คลิกยอมรับ

    แอปพลิเคชัน Python ทำงานและเรียกใช้ Google Drive Activity API

    ระบบจะจัดเก็บข้อมูลการให้สิทธิ์ไว้ในระบบไฟล์ ดังนั้นในครั้งถัดไปที่คุณเรียกใช้โค้ดตัวอย่าง ระบบจะไม่แจ้งให้ขอสิทธิ์

ขั้นตอนถัดไป