Google API:在调用get_credentials()时表单KeyError:'_ module'

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Google API:在调用get_credentials()时表单KeyError:'_ module'相关的知识,希望对你有一定的参考价值。

我在快速入门页面suggest上有与谷歌相似的代码。

from __future__ import print_function
import httplib2
import os

from apiclient import discovery
from oauth2client import client
from oauth2client import tools
from oauth2client.file import Storage

try:
    import argparse
    flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
except ImportError:
    flags = None

# If modifying these scopes, delete your previously saved credentials
# at ~/.credentials/sheets.googleapis.com-python-quickstart.json
SCOPES = 'https://www.googleapis.com/auth/spreadsheets.readonly'
CLIENT_SECRET_FILE = 'client_secret.json'
APPLICATION_NAME = 'Google Sheets API Python Quickstart'


def get_credentials():
    """Gets valid user credentials from storage.

    If nothing has been stored, or if the stored credentials are invalid,
    the OAuth2 flow is completed to obtain the new credentials.

    Returns:
        Credentials, the obtained credential.
    """
    home_dir = os.path.expanduser('~')
    credential_dir = os.path.join(home_dir, '.credentials')
    if not os.path.exists(credential_dir):
        os.makedirs(credential_dir)
    credential_path = os.path.join(credential_dir,
                                   'sheets.googleapis.com-python-quickstart.json')

    store = Storage(credential_path)
    credentials = store.get()
    if not credentials or credentials.invalid:
        flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
        flow.user_agent = APPLICATION_NAME
        if flags:
            credentials = tools.run_flow(flow, store, flags)
        else: # Needed only for compatibility with Python 2.6
            credentials = tools.run(flow, store)
        print('Storing credentials to ' + credential_path)
    return credentials

def main():
    """Shows basic usage of the Sheets API.

    Creates a Sheets API service object and prints the names and majors of
    students in a sample spreadsheet:
    https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit
    """
    credentials = get_credentials()
    http = credentials.authorize(httplib2.Http())
    discoveryUrl = ('https://sheets.googleapis.com/$discovery/rest?'
                    'version=v4')
    service = discovery.build('sheets', 'v4', http=http,
                              discoveryServiceUrl=discoveryUrl)

    spreadsheetId = '1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms'
    rangeName = 'Class Data!A2:E'
    result = service.spreadsheets().values().get(
        spreadsheetId=spreadsheetId, range=rangeName).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[4]))


if __name__ == '__main__':
    main()

首先,我创建了自己的秘密文件。然后执行没有该文件'sheets.googleapis.com-python-quickstart.json'和.credentials文件夹创建,但面临sheets.googleapis.com-python-quickstart.json: No such file or directory错误

那么我在该文件夹上创建了空文件sheets.googleapis.com-python-quickstart.json,但面临另一个错误KeyError: '_module'。我甚至试图将我的秘密文件重命名为sheets.googleapis.com-python-quickstart.json - 同样的错误。我已从控制台和ipython笔记本执行此代码 - 同样的错误。通过删除.readonly来改变SCOPES - 没有帮助

是否应该打开任何网页?我究竟做错了什么?

我的问题看起来与as相同 - 但没有任何帮助,我的问题应该是有点不同的想法

完整错误堆栈:

---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-83-58ca95c5b364> in <module>()
----> 1 main()

<ipython-input-82-1e078df2aa91> in main()
     37     https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit
     38     """
---> 39     credentials = get_credentials()
     40     http = credentials.authorize(httplib2.Http())
     41     discoveryUrl = ('https://sheets.googleapis.com/$discovery/rest?'

<ipython-input-82-1e078df2aa91> in get_credentials()
     20 
     21     store = Storage(credential_path)
---> 22     credentials = store.get()
     23 
     24     if not credentials or credentials.invalid:

~AppDataLocalContinuumAnaconda3libsite-packagesoauth2clientclient.py in get(self)
    405         self.acquire_lock()
    406         try:
--> 407             return self.locked_get()
    408         finally:
    409             self.release_lock()

~AppDataLocalContinuumAnaconda3libsite-packagesoauth2clientfile.py in locked_get(self)
     52 
     53         try:
---> 54             credentials = client.Credentials.new_from_json(content)
     55             credentials.set_store(self)
     56         except ValueError:

~AppDataLocalContinuumAnaconda3libsite-packagesoauth2clientclient.py in new_from_json(cls, json_data)
    300         # Find and call the right classmethod from_json() to restore
    301         # the object.
--> 302         module_name = data['_module']
    303         try:
    304             module_obj = __import__(module_name)

KeyError: '_module'
答案

首先应该下载适当的JSON,它应该是Web服务器。

其次,JSON应该包含重定向URL "redirect_uris":"http://localhost:8080/"

该网址也应该添加到Google帐户中的设置中,您刚刚生成了该JSON

以上是关于Google API:在调用get_credentials()时表单KeyError:'_ module'的主要内容,如果未能解决你的问题,请参考以下文章

中国的网站怎么调用Google 的API

调用 REST API 时如何处理 Google Ads API 速率限制?

Google Api,如何将访问令牌传递给API调用

从 Java 调用 Google Adwords api

如何在 CSS 文件中调用 Google API 字体? [复制]

错误:“用于调用 Google Play 开发者 API 的项目 ID 尚未在 Google Play 开发者控制台中链接。”