使用OAuth 2.0无法访问某些电子表格

时间:2019-05-16 02:48:02

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

对于Google API来说是新手,请遵循 Python Quickstart中有关基本程序的指示。决定使用我自己的API项目使该程序正常工作,并可以使用新凭据访问其示例表,但不能使用我自己的工作表。我要更改的只是SAMPLE_SPREADSHEET_ID,不太确定为什么我无法访问自己的电子表格。甚至将它们公开。在相关帐户上启用了Sheets API。

我收到此错误:

    {
  "error": {
    "code": 403,
    "message": "The request is missing a valid API key.",
    "status": "PERMISSION_DENIED"
  }
}

这里是程序:(我知道它很长,我只是绝望地问,因为谷歌搜索和折磨的日子无法解决我的问题)

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

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

# The ID and range of a sample spreadsheet.
SAMPLE_SPREADSHEET_ID = '1V7reDgXa4AuIa0hmf7cpr9SLxL0aZ0LuUXy3kBtR1uM'
SAMPLE_RANGE_NAME = 'Class Data!A1:C'


def main():

    """Shows basic usage of the Sheets API.
    Prints values from a sample spreadsheet.
    """
    creds = None
    # The file token.pickle 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.pickle'):
        with open('token.pickle', 'rb') as token:
            creds = pickle.load(token)
    # 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()
        # Save the credentials for the next run
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)

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

    # Call the Sheets API
    sheet = service.spreadsheets()
    result = sheet.values().get(spreadsheetId=SAMPLE_SPREADSHEET_ID,
                                range=SAMPLE_RANGE_NAME).execute()
    values = result.get('values', [])

    if not values:
        print('No data found.')
    else:
        print('Name, Major:')
        for row in values:
            # Print columns A and E, which correspond to indices 0 and 4.
            print('%s, %s' % (row[0], row[2]))


if __name__ == '__main__':
    main()

1 个答案:

答案 0 :(得分:0)

我可以看到这令人沮丧。如果需要,请尝试这种方式:


如果您的应用程序文件夹中有credentials.jsontoken.pickle文件以及quickstart.py程序,请删除credentials.jsontoken.pickle,仅保留{{ 1}}。

然后,运行quickstart.py,您会收到 python quickstart.py

的错误提示

接下来,转到(https://console.cloud.google.com/getting-started)并选择一个项目。您提到您决定使用“自己的API项目”,因此请选择该项目。

接下来,使用左侧的导航菜单,转到“ API和服务”>“库”,在“ G Suite”部分下,单击“ Google Sheets API”。验证是否显示“ API已启用”。如果尚未为此项目启用它,则将其启用。

接下来,使用左侧导航菜单,转到“ API和服务”>“凭据”,单击“创建凭据”>“帮助我选择”

接下来,在问题“您使用哪个API?”时,选择“ Google Sheets API”,然后在“您将从何处调用API?”问题,选择“其他用户界面(例如Windows,CLI工具)”,然后在问题“您将访问哪些数据?”选择“用户数据”

一旦您单击“我需要什么凭证?”按钮,它会告诉您“您已经有凭据”,或者会在“ OAuth 2.0客户端ID”下创建新的凭据

接下来,使用左侧的导航菜单,再次转到“ API和服务”>“凭据”,在“ OAuth 2.0客户端ID”下,您应该会看到一条记录,其中包含“名称”,“创建日期”等。在右侧,单击“下载JSON”的按钮。单击它,然后将文件另存为No such file or directory: 'credentials.json'在您的应用程序文件夹中。

现在您的应用程序文件夹中有两个文件,credentials.jsonquickstart.py

下一步,再次运行credentials.json

这将尝试在默认浏览器中打开新窗口或标签。如果失败,请从控制台复制URL,然后在浏览器中手动打开它。

如果您尚未登录Google帐户,则会提示您登录。如果登录了多个Google帐户,系统将要求您选择一个帐户进行授权。

在这里,我们正在讨论电子表格所属的Google帐户。选择帐户后,您应该会看到“授予...权限”模式。点击允许。

接下来,您应该再次看到“确认选择”面板,并带有“允许”按钮。单击它后,它转到“身份验证流程已完成,您可以关闭此窗口”。并且如果您检查应用程序文件夹,则会看到python quickstart.py文件已创建。

现在token.pickle应该可以访问您的电子表格了。


注意:python quickstart.py中的Class Data是Google示例中的标签页名称。您的电子表格的标签可能使用不同的名称。

相关问题