使用 Google Drive API 搜尋檔案名稱結果出現錯誤檔名

今天同事原本使用的 Google Drive 搜尋程式發生了一點問題,不知道為什麼今天搜尋到的檔案會出現多個之前都只有一個,看了一下是搜尋指令的問題。

有問題的程式範例

Google Drive API 提供非常多的搜尋條件可以用來使用,在使用上要注意一下搜尋條件讓它符合我們想要的結果,而搜尋條件的地方在 q 這個參數裡面,如下範例是使用 q="name contains '111/11/01 測試檔案'" 來當搜尋條件不過這個方法可能導致搜尋結果出現非預期的資料,所以我們可以做一點修改。

from __future__ import print_function

import google.auth
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError


def search_file():
    """Search file in drive location

    Load pre-authorized user credentials from the environment.
    TODO(developer) - See https://developers.google.com/identity
    for guides on implementing OAuth2 for the application.
    """
    creds, _ = google.auth.default()

    try:
        # create drive api client
        service = build('drive', 'v3', credentials=creds)
        files = []
        page_token = None
        while True:
            # pylint: disable=maybe-no-member
            response = service.files().list(q="name contains '111/11/01 測試檔案'",
                                            spaces='drive',
                                            fields='nextPageToken, '
                                                   'files(id, name)',
                                            pageToken=page_token).execute()
            for file in response.get('files', []):
                # Process change
                print(F'Found file: {file.get("name")}, {file.get("id")}')
            files.extend(response.get('files', []))
            page_token = response.get('nextPageToken', None)
            if page_token is None:
                break

    except HttpError as error:
        print(F'An error occurred: {error}')
        files = None

    return files


if __name__ == '__main__':
    search_file()

修改後結果

所以如果要比較精準的答案我們可以使用 q="name = '111/11/01 測試檔案'" 改成如下來避免出現問題

            response = service.files().list(q="name = '111/11/01 測試檔案'",
                                            spaces='drive',
                                            fields='nextPageToken, '
                                                   'files(id, name)',
                                            pageToken=page_token).execute()

參考資料