3

My application needs to upload some files daily, updating those that already exist.

I know that if I pass the ID of existing files, they will be updated, but I was wondering if there's some more clever solution for this.

def upload_file(path, folder, filename, drive):

    if not os.path.exists(path):
        print('Arquivo não encontrado: {}'.format(filename))
        return

   

    id_folder_destiny = get_id_from_gdrive(folder)
    file_metadata = {'title': filename, 
        'parents': [{'kind': 'drive#fileLink',
        'id': id_folder_destiny}]}
    file = drive.CreateFile(file_metadata)
       
    file.SetContentFile(path)
    file.Upload()

That code above is without the 'search existing ID'.

dawg
  • 98,345
  • 23
  • 131
  • 206

1 Answers1

2

The best solution I have found for updating a Google drive file is by uploading the file with the ID stated in the drive.CreateFile function, like you said. Here is my code for downloading and then overwriting the specific file.

def upload_file_to_drive(file_id, local_path):
    """Overwrites the existing Google drive file."""
    update_file = drive.CreateFile({'id': file_id})
    update_file.SetContentFile(local_path)
    update_file.Upload()

def download_drive_file(file_id, save_path):
    """Downloads an existing Google drive file."""
    download_file = drive.CreateFile({'id': file_id})
    download_file.GetContentFile(save_path)  

In use with an OOP class:

from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive

def get_google_drive_auth(self):
    """Initilaizes the Google drive 'drive' object. """
    gauth = GoogleAuth()

    # Try to load saved client credentials
    gauth.LoadCredentialsFile("path/to/your/credentials/file")

    if gauth.credentials is None:
        # Authenticate if they're not there
        gauth.GetFlow()
        gauth.flow.params.update({'access_type': 'offline'})
        gauth.flow.params.update({'approval_prompt': 'force'})
        gauth.LocalWebserverAuth()

    elif gauth.access_token_expired:
        # Refresh them if expired
        gauth.Refresh()
    else:
        # Initialize the saved creds
        gauth.Authorize()

    # Save the current credentials to a file
    gauth.SaveCredentialsFile("path/to/your/credentials/file")  

    self.drive = GoogleDrive(gauth)
    
def upload_file_to_drive(self, file_id, local_path):
    """Overwrites the existing Google drive file."""
    update_file = self.drive.CreateFile({'id': file_id})
    update_file.SetContentFile(local_path)
    update_file.Upload()
    
def download_drive_file(self,file_id, save_path):
    """Downloads an existing Google drive file."""
    download_file = self.drive.CreateFile({'id': file_id})
    download_file.GetContentFile(save_path)  # Save Drive file as a local file