相关文章推荐
有腹肌的充值卡  ·  pycharm console 清屏 ...·  2 月前    · 
爽快的大熊猫  ·  【Python】PyCharm ...·  3 周前    · 
小猫猫  ·  Web自动化测试—— ...·  6 天前    · 
稳重的枕头  ·  AttributeError: ...·  9 月前    · 
大力的红酒  ·  docker ...·  1 年前    · 
Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

google.auth.exceptions.DefaultCredentialsError: Could not automatically determine credentials

Ask Question

I am trying to follow https://developers.google.com/sheets/api/guides/values

I have the following python script:

from __future__ import print_function
import google.auth
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
def get_values(spreadsheet_id, range_name):
    Creates the batch_update the user has access to.
    Load pre-authorized user credentials from the environment.
    TODO(developer) - See https://developers.google.com/identity
    for guides on implementing OAuth2 for the application.
    creds, _ = google.auth.default()
    # pylint: disable=maybe-no-member
        service = build('sheets', 'v4', credentials=creds)
        result = service.spreadsheets().values().get(
            spreadsheetId=spreadsheet_id, range=range_name).execute()
        rows = result.get('values', [])
        print(f"{len(rows)} rows retrieved")
        return result
    except HttpError as error:
        print(f"An error occurred: {error}")
        return error
if __name__ == '__main__':
    # Pass: spreadsheet_id, and range_name
    get_values("id", "A1:C2")

I get the following error:

cchilders@cchilders-HP-ProBook-450-G3 ~/projects/update_stocks_interest_list $ python3 read_values.py 
Traceback (most recent call last):
  File "/home/cchilders/projects/update_stocks_interest_list/read_values.py", line 32, in <module>
    get_values("1N9hctlaS6gjRCVdpwgBx26dHr3tOFnE0125ybLuGvrk", "A1:C2")
  File "/home/cchilders/projects/update_stocks_interest_list/read_values.py", line 15, in get_values
    creds, _ = google.auth.default()
  File "/home/cchilders/.local/lib/python3.10/site-packages/google/auth/_default.py", line 616, in default
    raise exceptions.DefaultCredentialsError(_HELP_MESSAGE)
google.auth.exceptions.DefaultCredentialsError: Could not automatically determine credentials. Please set GOOGLE_APPLICATION_CREDENTIALS or explicitly create credentials and re-run the application. For more information, please see https://cloud.google.com/docs/authentication/getting-started
cchilders@cchilders-HP-ProBook-450-G3 ~/projects/update_stocks_interest_list $ ls
credentials.json  read_values.py

I logged into developers console and downloaded the Oauth2 file called client secret and renamed it to credentials.json as suggested online. The sheets api doc doesn't explain how google.auth loads credentials. I tried creating a .env file in the project folder and setting GOOGLE_APPLICATION_CREDENTIALS to credentials.json, the file in the same folder. It got the same error.

How can I get this script to work with my credentials?

GOOGLE_APPLICATION_CREDENTIALS should typically point to a service account file path.

From Google's docs on the topic, you'll want to:

  • Create a service account with the correct permissions for your service
  • Download that service account as a JSON file.
  • Point GOOGLE_APPLICATION_CREDENTIALS to the path of the JSON file, e.g. GOOGLE_APPLICATION_CREDENTIALS='/src/my-service-account.json'.
  • Specifics steps (credit Google documentation)

  • Create the service account: gcloud iam service-accounts create NAME

  • Add the permissions policy for the service account: gcloud projects add-iam-policy-binding PROJECT_ID --member="serviceAccount:SERVICE_ACCOUNT_NAME@PROJECT_ID.iam.gserviceaccount.com" --role=ROLE

  • Create the service account JSON file: gcloud iam service-accounts keys create FILE_NAME.json --iam-account=SERVICE_ACCOUNT_NAME@PROJECT_ID.iam.gserviceaccount.com

  • Export your environment variable in your current shell or a file that you source: export GOOGLE_APPLICATION_CREDENTIALS="KEY_PATH"

    For deployments I typically store service account credentials in some type of encrypted key storage service and download their contents as a build step, dynamically writing the file to memory or disk, depending on environment. This allows for easy updating/rotation/refactoring. Don't forget to remove the service account files from test and other container layers, if you do this! – Jason R Stevens CFA Aug 22, 2022 at 22:55

    Thanks for contributing an answer to Stack Overflow!

    • Please be sure to answer the question. Provide details and share your research!

    But avoid

    • Asking for help, clarification, or responding to other answers.
    • Making statements based on opinion; back them up with references or personal experience.

    To learn more, see our tips on writing great answers.

  •