我写了一个函数,该函数需要凭证并连接到Google工作表。我从googlesheet
中检索了数据,一切正常。由于某些原因,有时会给我一个错误。我搜索了一下,发现有一种解决方法,我在下面更改了代码。但是仍然是同样的问题。有人可以帮我吗?
那是我的代码:
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})
这是我下面的错误
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"
}
}
答案 0 :(得分:0)
我以前的代码
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()
正确答案
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()
答案 1 :(得分:0)
默认情况下,您会在1小时内获得expires令牌,因此这就是您必须再次运行的原因:
credentials=ServiceAccountCredentials.from_json_keyfile_name ('xxxx.json' , scope)
gs_client = gspread.authorize(credentials)
或者您也可以尝试:gc.login()