上传大文件无效 - Google Drive Python API

时间:2017-04-20 18:18:17

标签: python python-3.x api google-drive-api

此脚本适用于小文件,但在我尝试上传大文件(250MB)时则不适用。当我手动将相同的大文件上传到GD时,花费不到10秒,所以我认为我的连接不是问题。

upload.py

from __future__ import print_function
import os
import sys

from apiclient.http import MediaFileUpload
from apiclient.discovery import build
from httplib2 import Http
from oauth2client import file, client, tools

try:
    import argparse
    flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
except ImportError:
    flags = None

SCOPES = 'https://www.googleapis.com/auth/drive.file'
store = file.Storage(r'C:\Users\lucas.rezende\.credentials\storage.json')
creds = store.get()

if not creds or creds.invalid:
    flow = client.flow_from_clientsecrets(r'C:\Users\lucas.rezende\.credentials\client_secret.json', scope=SCOPES)
    creds = tools.run_flow(flow, store, flags) if flags else tools.run(flow, store)
DRIVE = build('drive', 'v3', http=creds.authorize(Http()))

FILES = (
    ('OfertasMensais_20170418_n.xlsx', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'),
)

for filename, mimeType in FILES:

    media_body = MediaFileUpload(filename, chunksize=1024*256, resumable = True)

    folder_id = '0000'
    metadata = {'name': filename, 'parents': [folder_id]}

    if mimeType:
        metadata['mimeType'] = mimeType
    res = DRIVE.files().create(body=metadata, media_body=filename).execute()

    if res:
        print('Uploaded "%s" (%s)' % (filename, res['mimeType']))

当我运行python uploadfile.py cmd时屏幕保持这样永恒:

enter image description here

有人可以帮助发现如何使这项工作?我不是一名专业的程序员,而且我坚持了近两个小时试图完成这项工作。

2 个答案:

答案 0 :(得分:0)

遵循分块范例,您需要专门致电next_chunk()继续上传。见这里:https://developers.google.com/api-client-library/python/guide/media_upload#resumable-media-chunked-upload

for filename, mimeType in FILES:
    media_body = MediaFileUpload(filename, chunksize=1024*256, resumable = True) 

    if mimeType:
        metadata['mimeType'] = mimeType

    req = DRIVE.files().insert(body=metadata, media_body=filename)
    res = None
    while res is None:
        status, res = req.next_chunk()
        if status :
            print('Uploading %d%% "%s" (%s)' % (status.progress(), filename, res['mimeType']))
    print("Upload Complete!")

答案 1 :(得分:0)

v3的解决方案是使用分块方法,但要使用create()函数,而不要使用insert()

        collapseOnSortingChange={true}
        collapseOnPageChange={true}
        collapseOnDataChange={true}