Google Drive API 对于非 Google 类型文件返回零文件夹大小

问题描述 投票:0回答:1

我需要获取 Google Drive 文件夹中所有文件的大小。我没有计算 Google 类型的文件(Google 表格等...)

这是代码

import os
from googleapiclient.discovery import build
# from google.oauth2.credentials import Credentials
from google.oauth2.service_account import Credentials as ServiceAccountCredentials

# Replace with the path to your JSON credentials file
JSON_CREDS_PATH = 'drivedownload-credentials.json'

# Shared folder ID
SHARED_FOLDER_ID = 'XXX-XXXXXXXXXXXXXXXXXXXXXXx'

def get_drive_service():
    # Load credentials from JSON file
    credentials = None
    if os.path.exists(JSON_CREDS_PATH):
        credentials = ServiceAccountCredentials.from_service_account_file(
            JSON_CREDS_PATH, scopes=['https://www.googleapis.com/auth/drive']
        )
    else:
        print("Credentials JSON file not found.")

    # Build the Google Drive API service
    if credentials:
        service = build('drive', 'v3', credentials=credentials)
        return service

def calculate_folder_size(service, folder_id):
    total_size = 0
    page_token = None
    while True:
        response = service.files().list(
            q=f"'{folder_id}' in parents",
            spaces='drive',
            fields='files(size), nextPageToken',
            pageToken=page_token
        ).execute()

        files = response.get('files', [])
        for file in files:
            total_size += int(file['size'])

        page_token = response.get('nextPageToken', None)
        if not page_token:
            break

    return total_size

def main():
    drive_service = get_drive_service()
    if drive_service:
        folder_size = calculate_folder_size(drive_service, SHARED_FOLDER_ID)
        print(f"Total size of files in the shared folder: {folder_size} bytes")

if __name__ == "__main__":
    main()

尺寸为零。

python google-drive-api
1个回答
0
投票

由于您使用的是服务帐户,因此您需要共享对服务帐户电子邮件的文件夹访问权限。您可以通过以下方式执行此操作:

1.) 单击文件夹上的三点 -> 共享

2.) 添加服务帐户电子邮件

您可以从服务帐户详细信息中获取服务帐户电子邮件

© www.soinside.com 2019 - 2024. All rights reserved.