Python - Gspread Request Error 401

前端 未结 2 1519
面向向阳花
面向向阳花 2021-02-09 16:41

I\'m currently making a Discord-bot that connects to a Google-spreadsheet (gspread). But after I\'ve been running it for a while it starts to hand out errors and it can\'t conne

相关标签:
2条回答
  • 2021-02-09 17:22

    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.
    
    0 讨论(0)
  • 2021-02-09 17:26

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

    0 讨论(0)
提交回复
热议问题