3

我尝试通过 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 上运行)上的其他用户使用,我不知道哪种解决方案是最好的。

谢谢您的帮助!

4

2 回答 2

2

您是否尝试过使用 PyDrive 库?

https://pypi.org/project/PyDrive/

您可以使用PyDrive包装库来获取可用于访问 Google Drive API 的高级函数。

PyDrive还使用 OAuth2.0,您只需几行即可进行设置:

from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive

gauth = GoogleAuth()
gauth.LocalWebserverAuth()

drive = GoogleDrive(gauth)

你可以得到一个像这样的文件:

# or download Google Docs files in an export format provided.
# downloading a docs document as an html file:
docsfile.GetContentFile('test.html', mimetype='text/html')

Wrapper 还允许您轻松创建和上传文件:

file1 = drive.CreateFile({'title': 'Hello.txt'})
file1.SetContentString('Hello')
file1.Upload() # Files.insert()

您可以使用我之前发送的链接获取更多文档和示例。干杯!

于 2021-05-20T16:07:01.147 回答
1

我最终使用了这段代码来帮助我实现它:

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 Drive 共享服务帐户地址
  • 如果您想访问共享驱动器,则需要 driveId
  • 对于共享驱动器,您需要将语料库、supportsAllDrives 和 includeItemsForAllDrives 设置为与代码中相同
  • 范围应与您的服务帐户在共享文件夹中的权限一致
于 2021-05-21T13:34:25.913 回答