为了账号安全,请及时绑定邮箱和手机立即绑定

PyDrive - 删除文件的内容

PyDrive - 删除文件的内容

ITMISS 2023-06-27 16:41:09
考虑以下使用PyDrive模块的代码:from 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.创建文件并更改其内容工作正常,直到我尝试通过将内容字符串设置为空字符串来擦除内容。这样做会引发此异常:pydrive.files.ApiRequestError<HttpError 400 when requestinghttps://www.googleapis.com/upload/drive/v2/files/{LONG_ID}?alt=json&uploadType=resumablereturned "Bad Request">当我查看云端硬盘时,我看到已成功创建test.txthello文件,其中包含文本。但我预计它会是空的。如果我将空字符串更改为任何其他文本,则文件会更改两次而不会出现错误。虽然这并没有清除内容,所以这不是我想要的。
查看完整描述

1 回答

?
江户川乱折腾

TA贡献1851条经验 获得超5个赞

问题和解决方法:

使用的时候resumable=True,好像0不能使用byte的数据。所以在这种情况下,需要上传空数据而不使用resumable=True. 但是当我看到PyDrive的脚本时,似乎它被resumable=True用作默认值。参考所以在这种情况下,作为一种解决方法,我想建议使用该requests模块。访问令牌是从gauthPyDrive 检索的。

当你的脚本被修改后,它会变成如下所示。

修改后的脚本:

import io

import requests

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.


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


查看完整回答
反对 回复 2023-06-27
  • 1 回答
  • 0 关注
  • 74 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信