RabidWolverine
RabidWolverine

Reputation: 46

Delete file in v3 with Python [Service Account]

I'm using Google Drive, and my code's using v3 for work with files by Service Account. I can read, download the file, but I can't delete. I tried with v2 delete (I don't find v3 delete) and no works(not permissions). I tried after with V2 impersonate admin account and no works.

Recently, I tried with this link but, no works for no scopes

def get_credenciales_with_impersonate():    
    delegated_credentials =  get_credenciales().create_delegated(admin_email)
    from httplib2 import Http
    http_auth = get_credenciales().authorize(Http())
    print(type(http_auth))
   return http_auth

...

serviceV2Impersonate = discovery.build('drive','v2',http=get_credenciales_with_impersonate())

My normal credentials is:

def get_credenciales():
    credenciales = ServiceAccountCredentials.from_p12_keyfile(
    client_email,p12_file)
    return credenciales

and works

serviceV2 = discovery.build('drive','v2',credentials=credentials)
serviceV3 = discovery.build('drive','v3',credentials=credentials)

How I could delete a file from drive with v3 and Python?

Upvotes: 0

Views: 2148

Answers (3)

otaku
otaku

Reputation: 1029

Example using Python Drive API.
There is an assumption below that the service account has access to the file with file_id

from apiclient import discovery
from google.oauth2 import service_account
import googleapiclient.discovery

SCOPES = ['https://www.googleapis.com/auth/drive']
SERVICE_ACCOUNT_FILE = 'service-account.json'
credentials = service_account.Credentials.from_service_account_file(SERVICE_ACCOUNT_FILE, scopes=SCOPES)
service = discovery.build('drive', 'v3', credentials=credentials)

# delete file using file id
file_id='<your file id here>'
service.files().delete(fileId=file_id).execute()

Reference:
https://developers.google.com/drive/api/v3/quickstart/python

Upvotes: 0

Teyam
Teyam

Reputation: 8082

There's Files: delete for Google Drive Rest API V3 using HTTP request format:

DELETE https://www.googleapis.com/drive/v3/files/fileId

However, please not that this is only possible if you use the owner's email which is the admin email.

Permanently deletes a file owned by the user without moving it to the trash. If the target is a folder, all descendants owned by the user are also deleted.

And since we can not transfer file ownership due to different domain issues, kindly try the given solution in this SO post - How to delete a google docs without ownership using an API/Services account. I hope it works.

Upvotes: 1

Kariamoss
Kariamoss

Reputation: 552

In v3, you have to call files.update with {'trashed':true}.

If you want to find a v3 function that you know exists, check Migrate to Google Drive API v3.

Upvotes: 0

Related Questions