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

时间:2018-02-21 16:57:40

标签: python python-3.x google-api google-oauth

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

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:

~\AppData\Local\Continuum\Anaconda3\lib\site-packages\oauth2client\client.py in get(self)
    405         self.acquire_lock()
    406         try:
--> 407             return self.locked_get()
    408         finally:
    409             self.release_lock()

~\AppData\Local\Continuum\Anaconda3\lib\site-packages\oauth2client\file.py in locked_get(self)
     52 
     53         try:
---> 54             credentials = client.Credentials.new_from_json(content)
     55             credentials.set_store(self)
     56         except ValueError:

~\AppData\Local\Continuum\Anaconda3\lib\site-packages\oauth2client\client.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'

1 个答案:

答案 0 :(得分:0)

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

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

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