PyDrive - 删除文件的内容

考虑以下使用PyDrive模块的代码:


from pydrive.auth import GoogleAuth

from pydrive.drive import GoogleDrive


gauth = GoogleAuth()

gauth.LocalWebserverAuth()

drive = GoogleDrive(gauth)


file = drive.CreateFile({'title': 'test.txt'})

file.Upload()


file.SetContentString('hello')

file.Upload()


file.SetContentString('')

file.Upload()    # This throws an exception.

创建文件并更改其内容工作正常,直到我尝试通过将内容字符串设置为空字符串来擦除内容。这样做会引发此异常:


pydrive.files.ApiRequestError

<HttpError 400 when requesting

https://www.googleapis.com/upload/drive/v2/files/{LONG_ID}?alt=json&uploadType=resumable

returned "Bad Request">

当我查看云端硬盘时,我看到已成功创建test.txthello文件,其中包含文本。但我预计它会是空的。


如果我将空字符串更改为任何其他文本,则文件会更改两次而不会出现错误。虽然这并没有清除内容,所以这不是我想要的。


ITMISS
浏览 80回答 1
1回答

江户川乱折腾

问题和解决方法:使用的时候resumable=True,好像0不能使用byte的数据。所以在这种情况下,需要上传空数据而不使用resumable=True. 但是当我看到PyDrive的脚本时,似乎它被resumable=True用作默认值。参考所以在这种情况下,作为一种解决方法,我想建议使用该requests模块。访问令牌是从gauthPyDrive 检索的。当你的脚本被修改后,它会变成如下所示。修改后的脚本:import ioimport requestsfrom pydrive.auth import GoogleAuthfrom pydrive.drive import GoogleDrivegauth = GoogleAuth()gauth.LocalWebserverAuth()drive = GoogleDrive(gauth)file = drive.CreateFile({'title': 'test.txt'})file.Upload()file.SetContentString('hello')file.Upload()# file.SetContentString()# file.Upload()    # This throws an exception.# I added below script.res = requests.patch(    "https://www.googleapis.com/upload/drive/v3/files/" + file['id'] + "?uploadType=multipart",    headers={"Authorization": "Bearer " + gauth.credentials.token_response['access_token']},    files={        'data': ('metadata', '{}', 'application/json'),        'file': io.BytesIO()    })print(res.text)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python