ตัวอย่างบัญชีบริการ Google Drive API Python

Oct 28 2020

เป็นไปได้ไหมที่จะตรวจสอบสิทธิ์กับ Google Drive API โดยใช้บัญชีบริการของ Google แทนที่จะใช้ขั้นตอน OAuth

ตัวอย่าง Python สำหรับ Google Drive ใช้ OAuth - Google drive Python Quick start

อย่างไรก็ตามฉันไม่พบตัวอย่างบัญชีบริการใด ๆ

ส่วนใหญ่ของ Google API ที่ผมใช้งานอื่น ๆ (แปลเมฆวิสัยทัศน์) ไม่ใช้บัญชีผู้ใช้บริการ แต่เพื่อให้ฉันต้องการที่จะเลิกใช้รหัส Google ไดรฟ์ OAuth ของฉันเพื่อความมั่นคง

คำตอบ

2 DaImTo Oct 28 2020 at 17:19

ตัวอย่าง python ของบัญชีบริการที่ดีที่สุดที่ฉันรู้จักคือตัวอย่างสำหรับGoogle Analytics

น่าจะเป็นอะไรประมาณนี้

from apiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials


SCOPES = ['https://www.googleapis.com/auth/drive.readonly']
KEY_FILE_LOCATION = '<REPLACE_WITH_JSON_FILE>'
VIEW_ID = '<REPLACE_WITH_VIEW_ID>'


def initialize_drive():
  """Initializes an service object.

  Returns:
    An authorized service object.
  """
  creds = ServiceAccountCredentials.from_json_keyfile_name(
      KEY_FILE_LOCATION, SCOPES)

  # Build the service object.
  service = build('drive', 'v3', credentials=creds)

  return service

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

อย่าลืมสร้างข้อมูลรับรองบัญชีบริการไม่ใช่ข้อมูลรับรอง Oauth