Python: authentication credentials Exception: "Request had invalid authentication credentials. Expected OAuth 2 access token"

Viewed 2229

I wrote function which takes credentials and connect to the google sheet. I retrieved the data from googlesheet and everything works normal. For some reason sometimes it gives me an error. I searched a bit and found out there is a way to solve it and i changed my code below. But still the same problem. can anybody help me please?

That is my code:

scope = ['https://spreadsheets.google.com/feeds',
     'https://www.googleapis.com/auth/drive']

credentials=ServiceAccountCredentials.from_json_keyfile_name ('xxxx.json' , scope)
gc = gspread.authorize(credentials)

wks = gc.open("Test")


def network_list(request,networkname=''):

gs_client = gspread.authorize(credentials)
sheet=wks.get_worksheet(2)

if credentials.access_token_expired:
      gs_client.login()  # refreshes the token

mylist = sheet.get_all_records()

listofvm=[]
for mydict in mylist:
    # print(mydict)
    for key, value in mydict.items():

        if mydict[key] == networkname:
            # print(mydict['Network']+'  ' + mydict['IP_address'] + ' ' + str(mydict['Total_Intentes']))
            # templist.append({'Build':mydict['Build'], 'VM_Name':mydict['VM_Name']})
            # print(mydict['VM_Name'])
            if mydict['VM_Name'] not in listofvm:
                listofvm.append(mydict['VM_Name'])


return render(request, 'vm_list.html',{'listofvm':listofvm, 'networkname':networkname})

And here is my error below

 APIError at /
 {
  "error": {
   "code": 401,
    "message": "Request had invalid authentication credentials. 
    Expected OAuth 2 access token, login cookie or other valid 
    authentication credential. See 
    https://developers.google.com/identity/sign-in/web/devconsole- 
    project.",
   "status": "UNAUTHENTICATED"
    }
  }
2 Answers

ok, folks, I found the answer. I just post here may be in the future somebody will need that one. All courses teach open google spreadsheet and then authorize your credentials but the key is here when you request to google sheet your tokens are changed that's why just before to request the data put "open" command after your credentials. I put here the right answer, I tried it, works very well.

My previous code

    scope = ['https://spreadsheets.google.com/feeds',
   'https://www.googleapis.com/auth/drive']

    credentials=ServiceAccountCredentials.from_json_keyfile_name ('xxxx.json' , scope)
    gc = gspread.authorize(credentials)

    wks = gc.open("Test")


    def network_list(request,networkname=''):

        gs_client = gspread.authorize(credentials)
        sheet=wks.get_worksheet(2)

        if credentials.access_token_expired:
            gs_client.login()  # refreshes the token

        mylist = sheet.get_all_records()

The right answer

    scope = ['https://spreadsheets.google.com/feeds',
    'https://www.googleapis.com/auth/drive']

    credentials=ServiceAccountCredentials.from_json_keyfile_name ('xxxx.json' , scope)
     gc = gspread.authorize(credentials)




     def network_list(request,networkname=''):

         gs_client = gspread.authorize(credentials)
         wks = gc.open("Test")
         sheet=wks.get_worksheet(2)

         if credentials.access_token_expired:
             gs_client.login()  # refreshes the token

         mylist = sheet.get_all_records()

Per default, the token you get expires within 1 hour, so that's why you will have to run again:

credentials=ServiceAccountCredentials.from_json_keyfile_name ('xxxx.json' , scope)
gs_client = gspread.authorize(credentials)

or also you can try: gc.login()

Related