我正在尝试连接到Google驱动器以下载文件,以供网络应用程序使用。我正在使用在Google Cloud控制台中生成的Service Accounts
密钥。当我使用API列出文件时,只有1个文件夹,但是当查看UI时,我看到了几个文件和1个文件夹(不是我在API中看到的一个文件夹)。
这是我使用的代码,表明我在做什么错吗?
from google.oauth2 import service_account
from googleapiclient.discovery import build
def init_connection():
SERVICE_ACCOUNT_FILE = 'credentials.json'
credentials = service_account.Credentials.from_service_account_file(SERVICE_ACCOUNT_FILE)
return credentials
def list_files():
creds = init_connection()
drive_service = build('drive', 'v3', credentials=creds)
# Call the Drive v3 API
results = drive_service.files().list(
pageSize=10, fields="nextPageToken, files(id, name)").execute(
print(results)
这个答案怎么样?
[从When I list the files with the API I get only 1 folder, but when I look at the UI I see a few files and 1 folder (not the one that I see with the API).
开始,我认为您可能已将从服务帐户中检索到的结果值与Google云端硬盘中显示的结果值进行了比较。如果是这样,则服务帐户的云端硬盘与您的Google云端硬盘不同。我认为这可能是您遇到问题的原因。
为了使用服务帐户检索Google云端硬盘中的文件和文件夹,以下解决方法如何?
在此替代方法中,包括了范围。
def init_connection():
SERVICE_ACCOUNT_FILE = 'credentials.json'
credentials = service_account.Credentials.from_service_account_file(SERVICE_ACCOUNT_FILE)
return credentials
至:def init_connection():
SERVICE_ACCOUNT_FILE = 'credentials.json'
SCOPES = ['https://www.googleapis.com/auth/drive.readonly']
credentials = service_account.Credentials.from_service_account_file(SERVICE_ACCOUNT_FILE, scopes=SCOPES)
return credentials
首先,在这种解决方法中,请与服务帐户的电子邮件共享Google云端硬盘中的示例文件夹。并且,使用以下脚本检索文件列表。
from google.oauth2 import service_account
from googleapiclient.discovery import build
def init_connection():
SERVICE_ACCOUNT_FILE = 'credentials.json'
credentials = service_account.Credentials.from_service_account_file(SERVICE_ACCOUNT_FILE)
# or, the following script.
# SCOPES = ['https://www.googleapis.com/auth/drive.readonly']
# credentials = service_account.Credentials.from_service_account_file(SERVICE_ACCOUNT_FILE, scopes=SCOPES)
return credentials
def list_files():
creds = init_connection()
drive_service = build('drive', 'v3', credentials=creds)
# Call the Drive v3 API
folderId = '###' # Please set the folder ID of the shared folder with the service account.
results = drive_service.files().list(pageSize=10, fields="nextPageToken, files(id, name)", q="'" + folderId + "' in parents").execute()
print(results)