PyDrive擦除文件的内容

2024-09-29 01:38:14 发布

您现在位置:Python中文网/ 问答频道 /正文

考虑使用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.txt文件,其中包含文本hello。然而,我希望它是空的

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

当我在互联网上查找错误时,我在PyDrive github上发现了这个issue可能与此有关,尽管它几乎一年都没有解决

如果你想重现这个错误,你必须创建你自己的项目,在PyDrive文档中使用googledriveapi

如何通过PyDrive擦除文件内容


Tags: 文件fromtestimporttxt内容drivefile
1条回答
网友
1楼 · 发布于 2024-09-29 01:38:14

问题和解决方法:

当使用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)

参考文献:

相关问题 更多 >