Skip to main content
 首页 » 编程设计

python之Google Drive API 上传超时

2024年10月24日8落叶

您如何诊断和修复 Google 无响应的 Drive API?

我正在尝试上传几个小文件,有时它运行完美,只需要几秒钟。其他时候它似乎无限期地挂起。我让它运行了一个小时,试图上传一个 1MB 的小文件。我不确定如何修复它,因为它没有抛出任何异常,权限似乎很好,而且我的 Internet 连接似乎足够快。这简直就是永远的,感觉幕后的事情已经超时了。

这是我的代码:

import httplib2 
import os 
 
from apiclient import discovery 
from apiclient.http import MediaFileUpload 
import oauth2client 
from oauth2client import client 
from oauth2client import tools 
 
SCOPES = 'https://www.googleapis.com/auth/drive' 
CLIENT_SECRET_FILE = 'my-app-secret-file.json' 
APPLICATION_NAME = 'my-app' 
 
def get_installed_app_credentials(): 
    """Gets valid user credentials from storage. 
 
    If nothing has been stored, or if the stored credentials are invalid, 
    the OAuth2 flow is completed to obtain the new credentials. 
 
    Returns: 
        Credentials, the obtained credential. 
    """ 
    home_dir = os.path.expanduser('~') 
    credential_dir = os.path.join(home_dir, '.credentials') 
    if not os.path.exists(credential_dir): 
        os.makedirs(credential_dir) 
    credential_path = os.path.join(credential_dir, 
                                   'drive-quickstart.json') 
 
    store = oauth2client.file.Storage(credential_path) 
    credentials = store.get() 
    if not credentials or credentials.invalid: 
        flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES) 
        flow.user_agent = APPLICATION_NAME 
        credentials = tools.run(flow, store) 
        print 'Storing credentials to ' + credential_path 
    return credentials 
 
def upload_file(): 
    credentials = get_installed_app_credentials() 
    http = credentials.authorize(httplib2.Http()) 
    service = discovery.build('drive', 'v2', http=http) 
 
    drive_folder_id = '0wlekrjelkjsfdBHYjdhb21CNm5' 
    filename = 'myfile.txt' 
    file = service.files().insert( 
        body={ 
            'title': filename, 
            'parents': [{'id': drive_folder_id}], 
        }, 
        media_body=MediaFileUpload( 
            filename, 
            resumable=True), 
    ).execute() 

请您参考如下方法:

驱动器上传速度很慢。建议使用可恢复上传并设置最小块大小 (256k)。可能值得深入研究您用来配置 block 大小的库,然后在每个 block 之后报告进度。