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">

当我查看云端硬盘时,我看到成功创建了带有文本hello test.txt 文件。但是我希望它是空的。

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

当我在Internet上查找错误时,尽管在将近一年仍未解决,但我在PyDrive github上发现了这个issue

如果要重现该错误,则必须根据PyDrive文档中的tutorial创建一个使用Google Drive API的项目。

如何通过PyDrive擦除文件内容

解决方法

问题和解决方法:

使用resumable=True时,似乎无法使用0字节的数据。因此,在这种情况下,需要在不使用resumable=True的情况下上传空数据。但是当我看到PyDrive的脚本时,似乎resumable=True被用作默认值。 Ref因此,在这种情况下,我想建议使用requests模块。访问令牌是从PyDrive的gauth检索的。

修改脚本后,它如下所示。

修改后的脚本:

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)

参考文献: