如何在 Google 驱动器上强制使用唯一的文件名?

How to enforce unique filenames on Google Drive?

我正在使用 Google 驱动器作为各种脚本存储常用文件的中心位置。然而,我注意到尽管假装像文件系统一样运行,Google 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"?我该如何防止这种情况?

  • 创建文件时,您只想在一个文件夹中指定一个文件名。
  • 当存在重复的文件名时,您不想创建该文件。
  • 您想使用云端硬盘 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。

参考文献:

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