如何使用PyDrive替换/更新Google云端硬盘上的文件?

时间:2019-05-10 17:32:17

标签: python python-3.x google-api google-drive-api pydrive

我的应用程序需要每天上传一些文件,更新已经存在的文件。

我知道,如果我传递现有文件的ID,它们会被更新,但是我想知道是否有更聪明的解决方案。

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()

上面的代码没有“搜索现有ID”。

1 个答案:

答案 0 :(得分:0)

我发现,更新Google云端硬盘文件的最佳解决方案是上传具有drive.CreateFile函数中所述ID的文件,就像您说的那样。 这是我的代码,用于下载然后覆盖特定文件。

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)  

与OOP类一起使用:

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