从谷歌 API 获取文件更改

问题描述 投票:0回答:1

我在谷歌指南中看到这一行https://developers.google.com/drive/api/guides/manage-changes?hl=en:

        if 'newStartPageToken' in response:
            # Last page, save this token for the next polling interval
            saved_start_page_token = response.get('newStartPageToken')
        page_token = response.get('nextPageToken')

但在我的例子中,'nextPageToken' 在响应字典中总是不存在。看起来像:

{
    'kind': 'drive#changeList',
    'newStartPageToken': '21',
    'changes': 
    [{
        'kind': 'drive#change',
        'removed': False,
        'file': 
        {
            'kind': 'drive#file',
            'mimeType': 'application/vnd.google-apps.spreadsheet',
            'id': '1fArmA72nxcQVv_gr31MHv4RV2e_n8j79-xvr6FOWDDc',
            'name': 'Canalservice'
        },
        'fileId': '1fArmA72nxcQVv_gr31MHv4RV2e_n8j79-xvr6FOWDDc',
        'time': '2023-03-18T08:39:23.049Z',
        'type': 'file',
        'changeType': 'file'
    }]
}

循环总是结束。有什么我不明白的想法吗?

python google-drive-api
1个回答
0
投票

我用这个示例代码尝试了

Get changes
。目前正在为我工作,如果你有什么不同,请告诉我。

from __future__ import print_function

import os.path

from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
from googleapiclient.http import MediaFileUpload


# If modifying these scopes, delete the file token.json.
SCOPES = ['https://www.googleapis.com/auth/drive', 
          'https://www.googleapis.com/auth/spreadsheets']


def fetch_changes(saved_start_page_token):
    creds = None
    if os.path.exists('token.json'):
        creds = Credentials.from_authorized_user_file('token.json', SCOPES)
    # If there are no (valid) credentials available, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open('token.json', 'w') as token:
            token.write(creds.to_json())


    try:
            # create drive api client
            service = build('drive', 'v3', credentials=creds)

            # Begin with our last saved start token for this user or the
            # current token from getStartPageToken()
            page_token = saved_start_page_token
            # pylint: disable=maybe-no-member

            while page_token is not None:
                response = service.changes().list(pageToken=page_token,
                                                spaces='drive').execute()
                for change in response.get('changes'):
                    # Process change
                    print(F'Change found for file: {change.get("fileId")}')
                if 'newStartPageToken' in response:
                    # Last page, save this token for the next polling interval
                    saved_start_page_token = response.get('newStartPageToken')
                page_token = response.get('nextPageToken')

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

    return saved_start_page_token


    
    
if __name__ == '__main__':
    # saved_start_page_token is the token number
    fetch_changes(saved_start_page_token=209)

参考:



更新:

(我只是在

print(response)
下面添加了一个
page_token = response.get('nextPageToken')
,或者您可以只添加
print(page_token)
以在每次迭代中获取页面令牌)

   if 'newStartPageToken' in response:
                    # Last page, save this token for the next polling interval
                    saved_start_page_token = response.get('newStartPageToken')
                    #print(saved_start_page_token)
                page_token = response.get('nextPageToken')
                print(response)

我从我发布的代码中得到的响应字典是:

{
  'kind': 'drive#changeList',
  'nextPageToken': '9199',
  'changes': [
    {
      'kind': 'drive#change',
      'removed': False,
      'file': {
        'kind': 'drive#file',
        'mimeType': 'text/javascript',
        'id': 'file-ID',
        'name': 'forge.min.js'
      },
      'fileId': 'file-ID',
      'time': '2023-02-24T15:40:21.690Z',
      'type': 'file',
      'changeType': 'file'
    },
    ...
    {
      'kind': 'drive#change',
      'removed': False,
      'file': {
        'kind': 'drive#file',
        'mimeType': 'video/vnd.dlna.mpeg-tts',
        'id': 'file-ID',
        'name': 'isbrowser.d.ts'
      },
      'fileId': 'file-ID',
      'time': '2023-02-24T15:40:25.988Z',
      'type': 'file',
      'changeType': 'file'
    }
  ]
}

请记住,所有文件和更改都嵌套在

response
中,并且
nextPageToken
列在每个循环响应的第一层中,而不是在文档
here
中提到的嵌套changes中。

{
  "kind": "drive#changeList",
  "nextPageToken": string,
  "newStartPageToken": string,
  "changes": [
    changes Resource
  ]
}

循环中的最后一次迭代将具有

newStartPageToken
而不是
nextPageToken
因为列表中不再有已更改的文件。

© www.soinside.com 2019 - 2024. All rights reserved.