3

我正在使用 Google Drive 作为各种脚本存储常用文件的中心位置。但是,我注意到尽管假装像文件系统一样运行,但 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”的重复上传?我将如何防止这种情况?

4

1 回答 1

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。

参考:

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

于 2019-04-24T22:16:45.760 回答