[英]Google Drive API Python Service Account Example
是否可以使用 Google 服務帳戶而不是 OAuth 流程對 Google Drive API 進行身份驗證?
Google Drive 使用 OAuth 的 Python 示例 - Google Drive Python 快速入門
但是我找不到任何服務帳戶示例。
但是,我使用的大多數其他 Google API(Translate、Cloud Vision)確實使用服務帳戶,因此我想棄用我的 Google Drive OAuth 代碼以保持一致性。
我所知道的最好的服務帳戶 python 示例是用於Google 分析的示例
它應該是這樣的。
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 憑據。
您可以使用以下方式使用 Credentials oauth2 對象,
import json
from google.oauth2.service_account import Credentials
SCOPES = ['https://www.googleapis.com/auth/drive']
service_account_info = json.load(open('service_account.json'))
creds=Credentials.from_service_account_info(
service_account_info, scopes=SCOPES)
drive_service = build('drive', 'v3', credentials=creds)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.