从 Python 调用 Google Drive 的 service.files().list().execute() 获得 NULL 响应

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

我一直在尝试使用 Python 获取

Google Drive
上的文件列表。

连接正在建立,但我从

NULL
呼叫中收到
service.files().list().execute()
响应。

Google 云端硬盘文件夹中肯定有文件。

这是我的代码:

# Function to list PDF files from Google Drive folder
def get_pdf_files_from_google_drive(folder_id, from_dt, to_dt):
    try:

        SCOPES = 'https://www.googleapis.com/auth/drive'
        creds = ServiceAccountCredentials.from_json_keyfile_name(SERVICE_ACCOUNT_FILE, SCOPES)

        service = build('drive', 'v3', credentials=creds)
        print(service.about().get(fields='user').execute())
        nextPageToken = None
        results = service.files().list(
                                    q="'{0}' in parents".format(folder_id),
                                    pageToken=nextPageToken,
                                    pageSize=5,
                                    fields="nextPageToken, files(id, name, modifiedTime)",
                                ).execute()
        items = results.get("files", [])
        nextPageToken = results.get("nextPageToken")

        # to iterate through nextPageToken here...

        return items
    except Exception as error:
        print("Got an exception:",error)

那个

print(service.about().get(fields='user').execute())

语句给出以下输出:

{'user': {'kind': 'drive#user', 'displayName': '[email protected]', 'photoLink': 'https://lh3.googleusercontent.com/a/default-user=YYY', 'me': True, 'permissionId': '123', 'emailAddress': '[email protected]'}}

这表明连接正在建立。

我是 Python 编程新手,对于可能出现的问题有什么想法吗?

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

所以这个解决方案被证明是相当愚蠢的。我必须与服务帐户共享 Google 云端硬盘文件夹。 这是供参考的工作代码:

def get_pdf_files_from_google_drive(folder_id):
    try:

        SCOPES = 'https://www.googleapis.com/auth/drive'
        creds = ServiceAccountCredentials.from_json_keyfile_name(SERVICE_ACCOUNT_FILE, SCOPES)

        service = build('drive', 'v3', credentials=creds)
        print(service.about().get(fields='user').execute())
        nextPageToken = None
        items = []
        while True:
            results = service.files().list(
                q="'{0}' in parents".format(folder_id),
                pageToken=nextPageToken,
                pageSize=5,
                fields="nextPageToken, files(id, name, modifiedTime)",
            ).execute()
            items.extend(results.get("files", []))
            nextPageToken = results.get("nextPageToken")
            if nextPageToken is None:
                break
        return items
    except Exception as error:
        print("Got an exception:",error)
© www.soinside.com 2019 - 2024. All rights reserved.