【问题标题】:PyDrive - Erase contents of a filePyDrive - 擦除文件的内容
【发布时间】:2020-08-26 22:35:00
【问题描述】:

考虑以下使用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 文档中的 tutorial 创建您自己的使用 Google Drive API 的项目。

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

【问题讨论】:

    标签: python python-3.x google-drive-api pydrive


    【解决方案1】:

    问题和解决方法:

    使用resumable=True的时候,好像不能使用0字节的数据。所以在这种情况下,需要上传空数据而不使用resumable=True。但是当我看到PyDrive的脚本时,似乎默认使用了resumable=TrueRef 所以在这种情况下,作为一种解决方法,我想建议使用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)
    

    参考资料:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-07
      相关资源
      最近更新 更多