【问题标题】:Google Drive API Python Service Account ExampleGoogle Drive API Python 服务帐户示例
【发布时间】:2021-02-10 16:31:48
【问题描述】:
是否可以使用 Google 服务帐户而不是 OAuth 流程对 Google Drive API 进行身份验证?
Google Drive 的 Python 示例使用 OAuth - Google drive Python Quick start
但是我找不到任何服务帐户示例。
我使用的大多数其他 Google API(翻译、Cloud Vision)确实使用服务帐户,因此我想弃用我的 Google Drive OAuth 代码以保持一致性。
【问题讨论】:
标签:
python-3.x
google-api
google-drive-api
google-api-python-client
service-accounts
【解决方案1】:
您可以通过以下方式使用 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)
【解决方案2】:
我所知道的最好的服务帐户 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 凭据。