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"
}
}