oauthgspreadpython-3.10

Using gspread with oauth and have to re-authorize every time I re-run my code


I'm trying to use gspread to access a google spreadsheet and I've been able to successfully do so, however, I have to re-authorize every time I run the code.

I've set up the credentials properly

As shown below, I specify a location for the authorized user file, and when I run the code the first time, it creates the authorized user file and the code runs with the expected results.

However, when running the code again, the oath method does not appear to read that file, and I have to authorize again. Once authorized again, the code runs as expected.

import gspread

SCOPES = ["https://www.googleapis.com/auth/spreadsheets"]
SPREADSHEET_ID = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"

CRED_FILE = "client_secret.json"
AUTH_USER_FILE = 'auth_user.json'

gc = gspread.oauth(credentials_filename=CRED_FILE, scopes=SCOPES, authorized_user_filename=AUTH_USER_FILE)

# Open a sheet from a spreadsheet in one go
spreadsheet = gc.open_by_key(SPREADSHEET_ID)

ws = spreadsheet.get_worksheet(0)

# Update a range of cells using the top left corner address
ws.update([[1, 2], [3, 4]], 'A1')

Am I missing something? Why does this require authorization every time it runs? I assumed the authorization with work until it expires.

Notably, I've been playing with the google api client a bit, and when playing with that, once authorized, I don't have to authorize again. The google api client is a bit over my head, so I wanted to switch over to using gspread.


Solution

  • The issue here turns out to be a bug in gspread 6.0.0.

    Downgrading to gspread 5.12.4 resolves the issue, and the bug fix is slated for release in gspread 6.0.1.

    Bug tracker is here: github.com/burnash/gspread/issues/1390