使用python将上传进度添加到Google云端硬盘脚本

时间:2018-11-23 19:12:47

标签: python google-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').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')

我想要添加进度条,所以我使用此documentation,将更改代码添加到:

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

1 个答案:

答案 0 :(得分:1)

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

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()