我一直在尝试使用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'
我搜索了它,甚至在此处进行了搜索,但找不到类似的东西。我知道我在做严重错误的事情,但无法确切说出什么。
答案 0 :(得分:0)
MediaIoBaseDownload
是googleapiclient.http
类中的方法,因此您可以在代码中包含以下行来解决此问题:
from googleapiclient.http import MediaIoBaseDownload
我解决了这部分问题,但是我仍然可以下载文件。