首页 > 解决方案 > 使用 python 将上传进度添加到 Google Drive 脚本

问题描述

这是我的代码:

media_body = MediaFileUpload(file_name , resumable=True)
body = {
    'title': file_name,
    'description': 'Uploaded By Bardulf'}
file = DRIVE.files().insert( body=body, media_body=media_body, fields='id, alternateLink').execute()
if file:
    print(file_name + " uploaded successfully")
prem = DRIVE.permissions().insert( fileId=file.get('id'), body={'type': 'anyone', 'value': 'anyone', 'role': 'reader', 'withLink': True}).execute()
print ("Your sharable link: "+ "https://drive.google.com/file/d/" + file.get('id')+'/view')

我想添加进度条,所以我使用这个文档,将我的代码添加到:

media_body = MediaFileUpload(file_name , resumable=True)
body = {
    'title': file_name,
    'description': 'Uploaded By Bardulf'}
file = DRIVE.files().insert( body=body, media_body=media_body, fields='id, alternateLink').execute()
if file:
    print(file_name + " uploaded successfully")
prem = DRIVE.permissions().insert( fileId=file.get('id'), body={'type': 'anyone', 'value': 'anyone', 'role': 'reader', 'withLink': True})
response = None
while response is None:
  status, response = prem.next_chunk()
  if status:
    print ("Uploaded %d%%." % int(status.progress() * 100))

print ("Your sharable link: "+ "https://drive.google.com/file/d/" + file.get('id')+'/view')

当我运行我的脚本时,我得到:

    status, response = prem.next_chunk()
  File "/usr/local/lib/python3.5/dist-packages/googleapiclient/_helpers.py", line 130, in positional_wrapper
    return wrapped(*args, **kwargs)
  File "/usr/local/lib/python3.5/dist-packages/googleapiclient/http.py", line 899, in next_chunk
    if self.resumable.size() is None:
AttributeError: 'NoneType' object has no attribute 'size'

我使用 api v2 和 python 3.5

标签: pythongoogle-drive-api

解决方案


您需要监控上传文件的进度,而不是设置权限:

media_body = MediaFileUpload(file_name, resumable=True)
body = {
    'title': file_name,
    'description': 'Uploaded By Bardulf'}
file = DRIVE.files().insert( body=body, media_body=media_body, fields='id, alternateLink')

response = None
while response is None:
  status, response = file.next_chunk()
  if status:
    print ("Uploaded %d%%." % int(status.progress() * 100))

if file:
    print(file_name + " uploaded successfully")
prem = DRIVE.permissions().insert( fileId=response.get('id'), body={'type': 'anyone', 'value': 'anyone', 'role': 'reader', 'withLink': True})

print ("Your sharable link: "+ "https://drive.google.com/file/d/" + response.get('id')+'/view')

execute()当您使用可恢复媒体时,您还需要删除该杂散。


推荐阅读