【问题标题】:Trouble accessing certain spreadsheets using OAuth 2.0使用 OAuth 2.0 访问某些电子表格时遇到问题
【发布时间】:2019-05-16 02:48:01
【问题描述】:

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()

【问题讨论】:

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


    【解决方案1】:

    我明白这有多令人沮丧。如果你愿意,试试这个方法:


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

    然后,运行python quickstart.py,你应该得到一个错误 No such file or directory: 'credentials.json'

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

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

    接下来,使用左侧导航菜单,转到“APIs & Services”>“Credentials”,点击“Create credentials”>“Help me choose”

    接下来,在“您使用的是哪个 API?”这个问题上,选择“Google Sheets API”,然后在“您将从哪里调用 API?”问题,选择“其他 UI(例如 Windows、CLI 工具)”,然后在问题“您将访问哪些数据?”选择“用户数据”

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

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

    现在您的应用程序文件夹中有两个文件,quickstart.pycredentials.json

    接下来,再次运行python quickstart.py

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

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

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

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

    现在python quickstart.py 应该可以访问您的电子表格了。


    注意:Class Data from SAMPLE_RANGE_NAME = 'Class Data!A1:C' 它是 Google 示例中的选项卡名称。您的电子表格可能有不同的选项卡名称。

    【讨论】: