python 从Google API获取文件更改

jhkqcmku  于 2023-03-21  发布在  Python
关注(0)|答案(1)|浏览(107)

我在谷歌指南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'
    }]
}

而且循环总是结束。有什么我没抓住的想法吗?

aiqt4smr

aiqt4smr1#

我尝试了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)

参考:

(我只是在page_token = response.get('nextPageToken')下面添加了一个print(response),或者您可以在每次迭代中添加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列在每个循环响应的第一层,而不是在这里的文档中提到的嵌套的changes中。

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

循环中的最后一次迭代将使用newStartPageToken而不是nextPageToken,因为列表中不再有已更改的文件。

相关问题