How to change Service Account owner from Uploaded files using Drive API

295 Views Asked by At

I have a lots of data about my employes in a spread sheet. I uploaded those data to my google drive using Drive API. I successfully uploaded the file with python script. But now all the files owner is service account that I created in Drive API.

I tried to change the owner to my current gmail account using python script. I can't change the owner, the script will stop with "You can't change the owner of a file owned by a service account." Error. How can I change the owner to default gmail account, because the all files are just shared with me, not own by me. If I disable to delete the service account, all the files are gone. I need to disable it after I uploaded all the files from my website to drive. What can I do?

my code:

import os
import pandas as pd
import json
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
from googleapiclient.http import MediaIoBaseUpload
from google.oauth2 import service_account
import requests
import io

# Define the ID of the file containing the credentials
json_file_id = 'json file location'

# Download the file
with open(json_file_id) as json_file:
    json_content = json.load(json_file)

    SCOPES = ['https://www.googleapis.com/auth/drive']

# create the credentials object
creds = service_account.Credentials.from_service_account_info(json_content, scopes=SCOPES)

service = build('drive', 'v3', credentials=creds)

file_id = 'file id as service account owner'
new_owner_email = 'current_account_gmail'

permission = {
    'type': 'user',
    'role': 'owner',
    'emailAddress': new_owner_email,
    'transferOwnership': True,
}
service.permissions().create(fileId=file_id, body=permission, transferOwnership=True, fields='id').execute()
0

There are 0 best solutions below