考虑使用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的hello文件。然而,我以为它会是空的。
如果我将空字符串更改为任何其他文本,则文件将被更改两次,而不会出现错误。虽然这不清楚内容,所以这不是我想要的。
当我在互联网上查找错误时,我发现这个问题在PyDrive github上可能是相关的,尽管它已经解决了将近一年。
如果您想要重现错误,您必须创建您自己的项目,使用Google跟踪这个教程文档中的PyDrive文档。
如何通过PyDrive删除文件的内容?
发布于 2020-08-26 23:50:04
问题和解决办法:
当使用resumable=True时,似乎无法使用0字节的数据。因此,在这种情况下,不使用resumable=True就需要上传空数据。但是,当我看到PyDrive的脚本时,似乎使用了resumable=True作为默认值。因此,在本例中,作为一种解决办法,我建议使用参考模块。访问令牌是从gauth of PyDrive检索的。
当您的脚本被修改时,如下所示。
修改脚本:
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)参考文献:
https://stackoverflow.com/questions/63606635
复制相似问题