“未找到请求的实体。”。详细信息:“未找到请求的实体。”>

时间:2021-03-23 15:54:45

标签: python google-sheets google-sheets-api google-api-python-client

我正在尝试使用 python 表 API 在我的谷歌表上应用过滤器。我收到此错误,并且没有任何提示可以调试此错误。我的代码看起来像这样。我尝试打印请求正文,其格式与 API 文档 (https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/request#setbasicfilterrequest) 中建议的格式完全相同。

我的代码如下:

from __future__ import print_function
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials

import pandas as pd
import json 

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

# The ID and range of a sample spreadsheet.
SAMPLE_SPREADSHEET_ID = '1ViILuxI3MD3vT7efWYDmlo5A67dIIDJbWXh6Pm9myPQ'
SAMPLE_RANGE_NAME = 'Sheet1!A2:I'

def main():
    """Shows basic usage of the Sheets API.
    Prints values from a sample spreadsheet.
    """
    creds = None
    # The file token.json stores the user's access and refresh tokens, and is
    # created automatically when the authorization flow completes for the first
    # time.
    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())

    service = build('sheets', 'v4', credentials=creds)

    _filter = {
        "range": {
            "sheetId": 0,
            "startRowIndex": 1,
            "startColumnIndex": 9,
            "endColumnIndex": 10
        },

        "criteria" : {
            9 : {
                "hiddenValues" : [
                    "Closed"
                ]
            }
        }
    }

    setBasicFilterRequest = {
        'setBasicFilter' : {
            'filter' : _filter
        }
    }

    body = { 
        'requests' : [setBasicFilterRequest],
        'includeSpreadsheetInResponse' : True,
        
    }

    # print(json.dumps(body, indent=4))
    resp = service.spreadsheets() \
   .batchUpdate(spreadsheetId="Sheet1", body=body).execute()

    print(resp)


if __name__ == '__main__':
    main()

运行时出现以下错误:

Traceback (most recent call last):
  File "poll_sheets.py", line 79, in <module>
    main()
  File "poll_sheets.py", line 72, in main
    resp = service.spreadsheets() \
  File "/Users/mike/Desktop/redash/myenv/lib/python3.8/site-packages/googleapiclient/_helpers.py", line 134, in positional_wrapper
    return wrapped(*args, **kwargs)
  File "/Users/mike/Desktop/redash/myenv/lib/python3.8/site-packages/googleapiclient/http.py", line 920, in execute
    raise HttpError(resp, content, uri=self.uri)
googleapiclient.errors.HttpError: <HttpError 404 when requesting https://sheets.googleapis.com/v4/spreadsheets/Sheet1:batchUpdate?alt=json returned "Requested entity was not found.". Details: "Requested entity was not found.">
(myenv) (base) mike@Mikes-MacBook-Pro redash % 

1 个答案:

答案 0 :(得分:2)

修改点:

  • 当我看到你的脚本时,似乎没有使用 SAMPLE_SPREADSHEET_ID
  • 关于 resp = service.spreadsheets().batchUpdate(spreadsheetId="Sheet1", body=body).execute(),您似乎使用工作表名称作为电子表格 ID。我认为这就是您出现问题的原因。

当以上几点反映到你的脚本中时,它变成如下。

修改后的脚本:

从:
resp = service.spreadsheets().batchUpdate(spreadsheetId="Sheet1", body=body).execute()
到:
resp = service.spreadsheets().batchUpdate(spreadsheetId=SAMPLE_SPREADSHEET_ID, body=body).execute()

注意:

  • 当您运行上面修改过的脚本并出现同样的错误时,请再次确认电子表格 ID。

参考: