簡體   English   中英

PyDrive - 擦除文件的內容

[英]PyDrive - Erase contents of a file

考慮以下使用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">

當我查看我的 Drive 時,我看到test.txt文件已成功創建,其中包含文本hello 但是我預計它會是空的。

如果我將空字符串更改為任何其他文本,則文件會更改兩次而不會出錯。 雖然這並沒有清除內容,所以這不是我想要的。

我在網上查了這個錯誤,在PyDrive github上發現了這個問題,這個問題可能是相關的,雖然已經快一年沒有解決了。

如果要重現該錯誤,則必須按照 PyDrive 文檔中的本教程創建自己的使用 Google Drive API 的項目。

如何通過 PyDrive 擦除文件的內容?

問題和解決方法:

使用resumable=True的時候,好像不能使用0字節的數據。 所以在這種情況下,需要在不使用resumable=True情況下上傳空數據。 但是當我看到PyDrive的腳本時,似乎默認使用了resumable=True Ref所以在這種情況下,作為一種解決方法,我想建議使用requests模塊。 訪問令牌是從gauth的 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)

參考:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM