上传大文件不工作谷歌驱动Python API

2024-06-20 15:06:09 发布

您现在位置:Python中文网/ 问答频道 /正文

这个脚本适用于小文件,但当我试图上传一个大文件(250MB)时就不行了。当我手动将同一个大文件上传到GD时,只需不到10秒,所以我假设我的连接不是问题所在。在

上传.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命令时,屏幕始终保持不变:

enter image description here

有人能帮我发现如何使这个工作吗?我不是一个专业的程序员,我被困在这几乎两个小时,试图使这个工作。在


Tags: 文件storefromimportclientifbodyfilename
2条回答

遵循chunked范式,您需要特别调用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!")

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

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

            DRIVE = self.drive.files().create(body=metadata,media_body=media_body)
            while res is None:
                status, res = drive_request.next_chunk()

相关问题 更多 >