【问题标题】:How to enforce unique filenames on Google Drive?如何在 Google Drive 上强制使用唯一的文件名?
【发布时间】:2019-04-25 06:16:45
【问题描述】:

我使用 Google 云端硬盘作为各种脚本存储常用文件的中心位置。但是,我注意到尽管假装像文件系统一样运行,但 Google Drive 并没有遵守正常的文件系统约定,例如强制使用唯一的文件名。这允许不同的用户上传具有相同文件名的单独文件。

有什么办法可以防止这种情况发生吗?

我的脚本都使用相同的代码来访问 Drive API 以上传文件:

import os
import httplib2
from apiclient import discovery, errors
from apiclient.http import MediaFileUpload

credentials = get_google_drive_credentials()
service = discovery.build('drive', 'v2', http=credentials.authorize(httplib2.Http()))

dir_id = 'google_drive_folder_hash'
filename = '/some/path/blah.txt'
service.files().insert(
    body={
        'title': os.path.split(filename)[-1],
        'parents': [{'id': dir_id}],
    },
    media_body=MediaFileUpload(filename, resumable=True),
).execute()

如果两个或更多脚本运行此代码,并假设没有竞争条件,为什么此代码会导致“blah.txt”重复上传?我将如何防止这种情况发生?

【问题讨论】:

    标签: python flysystem-google-drive


    【解决方案1】:
    • 创建文件时,您只想在文件夹中指定一个文件名。
    • 当重复的文件名存在时,您不想创建该文件。
    • 您想使用 Drive API v2。

    如果我的理解是正确的,那么这个答案呢?在这个答案中,添加了在文件夹中搜索重复文件名的过程。为此,我使用了 files.list 方法。该脚本的流程如下。

    1. 检索文件夹中title的文件。
    2. 如果重复的文件名不存在,则创建新文件。
    3. 如果存在重复的文件名,则不会创建新文件。

    示例脚本:

    res = service.files().list(q="title='" + title + "' and '" + dir_id + "' in parents", fields="items(id,title)").execute()
    if len(res['items']) == 0:
        # In this case, no duplicated filename is existing.
        service.files().insert(
            body={
                'title': title,
                'parents': [{'id': dir_id}],
            },
            media_body=MediaFileUpload(filename, resumable=True),
        ).execute()
    else:
        # In this case, the duplicated filename is existing.
        # Please do error handling here, if you need.
        print("Duplicated files were found.")
    

    注意:

    • 此修改后的脚本假设您已经使用过 Drive API。

    参考资料:

    如果我误解了您的问题并且这不是您想要的结果,我深表歉意。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多