python - 上传大文件不起作用 - Google Drive Python API

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

此脚本适用于小文件,但不适用于我尝试上传大文件 (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时,cmd屏幕永远保持这样:

enter image description here

有人可以帮助了解如何实现这项工作吗?我不是一个专业的程序员,我花了将近两个小时来尝试让这项工作成功。

最佳答案

按照分块范例,您需要专门调用 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!")

关于python - 上传大文件不起作用 - Google Drive Python API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43527012/

相关文章:

python - Django - PostgreSQL 设置 statement_timeout

python - 按下按钮后多次更改 tkinter 输入小部件

python - 从另一列的子字符串创建列

api - REST API 具有相同的对象,但很轻

python - 跨项目的 Cython 定义?

python - 在 Python 中处理传递性

python-3.x - 如何使用 'random' 和 'networkX' 库生成图形?

python - Python中的无限整数

api - 在艺术家的轨道中搜索 - Spotify API

php - CURL php 不会接受 Accept-Language : fr needed to get the JSON