Google 驱动器 API Python 服务帐户示例
Google Drive API Python Service Account Example
是否可以使用 Google 服务帐户而不是 OAuth 流程对 Google 驱动器 API 进行身份验证?
Google 驱动器使用 OAuth 的 Python 示例 - Google drive Python Quick start
但是我找不到任何服务帐户示例。
我使用的其他 Google API 中的大多数(翻译,Cloud Vision)确实 使用服务帐户,所以我想弃用我的 Google Drive OAuth 代码以保持一致性。
我知道的最好的服务帐户 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 凭据。
您可以通过以下方式使用 Credentials oauth2 对象,
import json
from googleapiclient.discovery import build
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)
是否可以使用 Google 服务帐户而不是 OAuth 流程对 Google 驱动器 API 进行身份验证?
Google 驱动器使用 OAuth 的 Python 示例 - Google drive Python Quick start
但是我找不到任何服务帐户示例。
我使用的其他 Google API 中的大多数(翻译,Cloud Vision)确实 使用服务帐户,所以我想弃用我的 Google Drive OAuth 代码以保持一致性。
我知道的最好的服务帐户 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 凭据。
您可以通过以下方式使用 Credentials oauth2 对象,
import json
from googleapiclient.discovery import build
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)