繁体   English   中英

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

[英]How to access shared Google Drive files through Python?

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

谢谢您的帮助!

您是否尝试过使用 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()

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

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

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 设置为与代码中相同
  • scope 应与您的服务帐户在共享文件夹中的权限一致

我使用了 pydrive2 以下代码为我工作

from pydrive2.auth import GoogleAuth
from oauth2client.service_account import 
ServiceAccountCredentials
from pydrive2.drive import GoogleDrive

gauth = GoogleAuth()

gauth.credentials = ServiceAccountCredentials.from_json_keyfile_name('credentials.json', SCOPES)
drive = GoogleDrive(gauth)
query = "'{}' in parents and trashed=false"
query=query.format(folder_id)
file_list = drive.ListFile({'q': query}).GetList()

确保凭据文件位于同一文件夹中,并且您尝试访问的驱动器与创建您的服务或开发人员帐户的 email 共享该文件夹。 有关更多详细信息,请参阅我的博客https://medium.com/@zakriya57/integrating-google-drive-in-your-application-1c3012fef396

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM