Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to trash files in Google Drive API v3, python client

I need to trash a file by using the Google Drive API V3. While V2 has a trash method, V3 doesn't have one. Instead, you need to modify the file's metadata.

I've searched everywhere but couldn't find an answer for this. I've found an example for Android here in stackoverflow, but I don't know how to translate it into python: Google Drive Rest API v3 - how to move a file to the trash?.

Here's the function that's supposed to trash the files:

def trashFile(service, file_id):
        # First retrieve the file from the API.
        file = service.files().get(fileId=file_id,fields="trashed" ).execute()

        # File's new metadata.
        file['trashed'] = True

        # Send the request to the API.
        updated_file = service.files().update(body=file).execute()
        return updated_file
        return None

Everything runs smoothly, the file is retrieved, the file ID is correct, the update command is executed, but the file is not trashed.

What should I do? Thanks in advance for your help.

like image 630
Clement Bjelland Avatar asked Nov 24 '25 13:11

Clement Bjelland


1 Answers

  • You want to move a file to the trash using Drive API v3 by the Google Client Library with Python.

I could understand like above. In order to achieve this, how about this modification?

Modified script 1:

If your script is modified, please modify as follows.

From:
updated_file = service.files().update(body=file).execute()
To:
updated_file = service.files().update(fileId=file_id, body=file).execute()

Modified script 2:

For example, how about this modified script? In this case, it can be achieved by one API call.

def trashFile(service, file_id):
    body = {'trashed': True}
    updated_file = service.files().update(fileId=file_id, body=body).execute()
    return updated_file

Note:

  • If the file you want to move the trash is NOT your file, the file might not be able to be moved. Please be careful this.

Reference:

  • Files: update
like image 117
Tanaike Avatar answered Nov 26 '25 04:11

Tanaike



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!