2

The instructions for authentication can be found here: https://gspread.readthedocs.io/en/latest/oauth2.html#for-end-users-using-oauth-client-id

Step 7 in the authentication sequence says: "Move the downloaded file to ~/.config/gspread/credentials.json. Windows users should put this file to %APPDATA%\gspread\credentials.json"

Is anyone aware of a way to keep the credentials.json file somewhere else and use it to authorize gpread?

Alternatively I have thought about using shutil.move to grab the json file move it to the desired location but need to be able to do that without making assumptions about the whereabout of the python library or even if it is on a windows or unix machine. Any environmental variables that would reveal location of certain libraries?I could do something like this:

import gspread, os, shutil
loc = gspread.__location__
cred_path = os.path.join(loc, "credentials.json")
if not os.path.isfile(cred_path):
    shutil.move(input("Enter creds path:"), cred_path)
ChungaBunga
  • 116
  • 1
  • 10

1 Answers1

1

Found the solution to my own question. This function will set all the relevant environmental variables to your directory of choice where the credentials.json file should be kept (and the authorized_user.json file.):

import gspread.auth as ga
def gspread_paths(dir):
    ga.DEFAULT_CONFIG_DIR = dir
    ga.DEFAULT_CREDENTIALS_FILENAME = os.path.join(
        ga.DEFAULT_CONFIG_DIR, 'credentials.json')
    ga.DEFAULT_AUTHORIZED_USER_FILENAME = os.path.join(
        ga.DEFAULT_CONFIG_DIR, 'authorized_user.json')
    ga.DEFAULT_SERVICE_ACCOUNT_FILENAME = os.path.join(
        ga.DEFAULT_CONFIG_DIR, 'service_account.json')
    ga.load_credentials.__defaults__ = (ga.DEFAULT_AUTHORIZED_USER_FILENAME,)
    ga.store_credentials.__defaults__ = (ga.DEFAULT_AUTHORIZED_USER_FILENAME, 'token')

EDIT: Recently there was a merged pull request that added this functionality to gspread: https://github.com/burnash/gspread/pull/847

ChungaBunga
  • 116
  • 1
  • 10
  • It says ModuleNotFoundError No module named 'gspread.auth'; 'gspread' is not a package – Egret Sep 22 '21 at 09:34
  • Did you install gspread? import gspread? They did implement using custom credential paths in the recently: https://github.com/burnash/gspread/pull/847 – ChungaBunga Sep 27 '21 at 23:37