gpt4 book ai didi

Python - 无法使用 Google Drive API 从 Google Drive 下载文件

转载 作者:太空宇宙 更新时间:2023-11-03 21:29:25 25 4
gpt4 key购买 nike

我一直在尝试使用 Google Drive API 自动从 Google Drive 下载一些文件,并选择使用 Python 3.6.5 来执行此操作。

一开始,我按照quickstart sample (效果很好)然后移至 download files sample ,这就是头痛开始的时候。首先,我只是在下面的代码中“融合”了两个示例:

from __future__ import print_function
from apiclient import discovery
from googleapiclient.discovery import build
from httplib2 import Http
from oauth2client import file, client, tools
import io
# from oauth2client import client
# from oauth2client import tools

SCOPES = 'https://www.googleapis.com/auth/drive.metadata.readonly'

def main():


store = file.Storage('token.json')
creds = store.get()
if not creds or creds.invalid:
flow = client.flow_from_clientsecrets('credentials.json', SCOPES)
creds = tools.run_flow(flow, store)
service = build('drive', 'v3', http=creds.authorize(Http()))

file_id = 'myfileID'
request = drive_service.files().get_media(fileId=file_id)
fh = io.BytesIO()
downloader = MediaIoBaseDownload(fh, request)
done = False
while done is False:
status, done = downloader.next_chunk()
print "Download %d%%." % int(status.progress() * 100)


if __name__ == '__main__':
main()

但它不起作用,Python 无法识别 MediaIoBaseDownload。然后我继续执行以下代码:

from __future__ import print_function
from apiclient import discovery
from googleapiclient.discovery import build
from httplib2 import Http
from oauth2client import file, client, tools
import io
# from oauth2client import client
# from oauth2client import tools

SCOPES = 'https://www.googleapis.com/auth/drive.metadata.readonly'

def main():


store = file.Storage('token.json')
creds = store.get()
if not creds or creds.invalid:
flow = client.flow_from_clientsecrets('credentials.json', SCOPES)
creds = tools.run_flow(flow, store)
service = build('drive', 'v3', http=creds.authorize(Http()))

file_id = 'myfileID'
request = service.files().get_media(fileId=file_id)

fh = io.BytesIO()
with open('mydestinationFile', 'wb') as f:
f.write(request)

done = False
while done is False:
status, done = downloader.next_chunk()
print("Download %d%%." % int(status.progress() * 100))


if __name__ == '__main__':
main()

现在出现错误:

Traceback (most recent call last):
File "Google API.py", line 50, in <module>
main()
File "Google API.py", line 32, in main
f.write(request)
TypeError: a bytes-like object is required, not 'HttpRequest'

我用谷歌搜索了它,甚至在这里搜索了SO,但找不到类似的东西。我知道我做了一些严重错误的事情,但无法确切地说出什么。

最佳答案

MediaIoBaseDownloadgoogleapiclient.http 类中的一个方法,因此您可以在代码中包含以下行来解决此问题:

from googleapiclient.http import MediaIoBaseDownload

我解决了这部分问题,但我仍然可以下载文件。

关于Python - 无法使用 Google Drive API 从 Google Drive 下载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53621316/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com