Rocketq
Rocketq

Reputation: 5791

Google API: sheets KeyError: '_module' while calling get_credentials()

I have pretty similar code as google on a quick start page 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()

Firstly, I created my own secret file. Then executed without that file 'sheets.googleapis.com-python-quickstart.json' and .credentials folder was created, but faced sheets.googleapis.com-python-quickstart.json: No such file or directory error

So then I created that empty file sheets.googleapis.com-python-quickstart.json on that folder, but faced another error KeyError: '_module'. I even tried to rename my secret file as sheets.googleapis.com-python-quickstart.json - same error. I have executed this code from console and from ipython notebook - same error. Changing SCOPES by deleting .readonly - didn't help

Is there any webpage should be opened? What am I doing wrong?

My question looks the same as - but nothing helped and my question should be about a bit different think

Full error stack:

---------------------------------------------------------------------------
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'

Upvotes: 0

Views: 2228

Answers (1)

Rocketq
Rocketq

Reputation: 5791

First of all proper JSON should be downloaded, it should be for web server.

Secondly that JSON should contain redirect URL "redirect_uris":"http://localhost:8080/"

That URL also should be added to settings in the google account, where you have just generated that JSON

Upvotes: 1

Related Questions