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



我一直在尝试使用Google Drive API自动从我的Google Drive下载一些文件,选择使用Python 3.6.5来实现这一点。

起初,我遵循了快速启动示例(效果很好(,然后转到下载文件示例,这就是头疼的开始。起初,我只是在下面的代码中"融合"了两个样本:

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

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

如果你想下载文件,你需要更改io.BytesIO的使用

发件人:

fh = io.BytesIO()

收件人:

fh = io.FileIO("### filename ###", mode='wb')

最新更新