简体   繁体   中英

PyDrive - Erase contents of a file

Consider the following code that uses the PyDrive module:

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.

Creating file and changing its contents works fine until I try to erase the contents by setting the content string to an empty one. Doing so throws this 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">

When I look at my Drive, I see the test.txt file successfully created with text hello in it. However I expected that it would be empty.

If I change the empty string to any other text, the file is changed twice without errors. Though this doesn't clear the contents so it's not what I want.

When I looked up the error on the Internet, I found this issue on PyDrive github that may be related though it remains unsolved for almost a year.

If you want to reproduce the error, you have to create your own project that uses Google Drive API following this tutorial from the PyDrive docs.

How can one erase the contents of a file through PyDrive?

Issue and workaround:

When resumable=True is used, it seems that the data of 0 byte cannot be used. So in this case, it is required to upload the empty data without using resumable=True . But when I saw the script of PyDrive, it seems that resumable=True is used as the default. Ref So in this case, as a workaround, I would like to propose to use the requests module. The access token is retrieved from gauth of PyDrive.

When your script is modified, it becomes as follows.

Modified script:

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)

References:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM