首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >PyDrive -删除文件的内容

PyDrive -删除文件的内容
EN

Stack Overflow用户
提问于 2020-08-26 22:35:00
回答 1查看 285关注 0票数 1

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

代码语言:javascript
复制
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.

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

代码语言:javascript
复制
pydrive.files.ApiRequestError
<HttpError 400 when requesting
https://www.googleapis.com/upload/drive/v2/files/{LONG_ID}?alt=json&uploadType=resumable
returned "Bad Request">

当我查看我的驱动器时,我看到成功地创建了包含文本hellohello文件。然而,我以为它会是空的。

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

当我在互联网上查找错误时,我发现这个问题在PyDrive github上可能是相关的,尽管它已经解决了将近一年。

如果您想要重现错误,您必须创建您自己的项目,使用Google跟踪这个教程文档中的PyDrive文档。

如何通过PyDrive删除文件的内容?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-08-26 23:50:04

问题和解决办法:

当使用resumable=True时,似乎无法使用0字节的数据。因此,在这种情况下,不使用resumable=True就需要上传空数据。但是,当我看到PyDrive的脚本时,似乎使用了resumable=True作为默认值。因此,在本例中,作为一种解决办法,我建议使用参考模块。访问令牌是从gauth of PyDrive检索的。

当您的脚本被修改时,如下所示。

修改脚本:

代码语言:javascript
复制
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)

参考文献:

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63606635

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档