Python - Gspread Request Error 401

ⅰ亾dé卋堺 提交于 2019-12-03 09:13:17

Your access token expires after some period of time. From the OAuth 2.0 docs:

  1. Refresh the access token, if necessary.

Access tokens have limited lifetimes. If your application needs access to a Google API beyond the lifetime of a single access token, it can obtain a refresh token. A refresh token allows your application to obtain new access tokens.

Note: Save refresh tokens in secure long-term storage and continue to use them as long as they remain valid. Limits apply to the number of refresh tokens that are issued per client-user combination, and per user across all clients, and these limits are different. If your application requests enough refresh tokens to go over one of the limits, older refresh tokens stop working.

I don't believe that gspread is equipped to deal with refresh tokens. You may just be able to catch this exception and reauthenticate as needed.

EDIT:

After looking at the gspread source I think you may be able to refresh your token by simply calling gc.login()

EDIT:

This issue was filed with gspread a couple of years ago but it was closed for no apparent reason. Here is one approach to solving it:

def add_row(row):
    try:
        gs_client = gspread.authorize(creds)
        gs_worksheet = gs_client.open("foo").sheet1
        if creds.access_token_expired:
            gs_client.login()  # refreshes the token
        gs_worksheet.append_row(row)
    except Exception, e:
        traceback.print_exc()

but I think that's overkill. You should be able to just call gc.login() right before your try: block:

gc.login()
try:
    #Try to find the username in spreadsheet.
    cell_name = worksheet.find(Username)
except: #If we dont find the username.

The only plausible culprit here is your account credentials. Try creating new credentials on your Google Developer Console and using that.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!