如何通过 Python 访问共享的 Google Drive 文件?

问题描述

我尝试通过 Python 访问共享的 Google Drive 文件

我已经创建了 OAuth 2.0 ClientID 以及 OAuth 同意书。

我已复制粘贴此代码https://github.com/googleworkspace/python-samples/blob/master/drive/quickstart/quickstart.py

授权成功,但是Python代码返回一个空白列表,表明Google Drive中没有文件,尽管有很多。

是否应该有区别,因为我正在尝试访问共享文件夹,如果是,是否会导致错误,以及如何解决

如果不是,这是正确的方法吗?我也阅读了 API 密钥和服务帐户,使用它们中的任何一个有意义吗?稍后我创建的这项服务将被 Databricks(在 AWS 上运行)上的其他用户使用,我不知道哪种解决方案是最好的。

感谢您的帮助!

解决方法

我最终使用了帮助我实现它的代码:

from __future__ import print_function
from googleapiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials

scope = ['https://www.googleapis.com/auth/drive.readonly']

credentials = ServiceAccountCredentials.from_json_keyfile_name('service_account_key.json',scope)

# https://developers.google.com/drive/api/v3/quickstart/python
service = build('drive','v3',credentials=credentials)

# Call the Drive v3 API
results = service.files().list(
    fields="*",corpora = 'drive',supportsAllDrives = True,driveId = "YOUR_DRIVE_ID",includeItemsFromAllDrives = True).execute()
items = results.get('files',[])

if not items:
    print('No files found.')
else:
    print('Files:')
    for item in items:
        print(u'{0} ({1})'.format(item['name'],item['id']))

服务帐户很重要,因为这样用户就不需要逐一验证自己的身份。

此解决方案的关键要点:

  • 您需要与 Google 云端硬盘共享服务帐户地址
  • 如果您想访问共享驱动器,则需要 driveId
  • 对于共享驱动器,您需要将语料库、supportsAllDrives 和 includeItemsForAllDrives 设置为与代码中相同
  • 范围应与您的服务帐户在共享文件夹中拥有的权限保持一致

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...