Python:身份验证凭据异常:“0”;请求具有无效的身份验证凭据。预期OAuth 2访问令牌“;
我编写了一个函数,它可以获取凭据并连接到google工作表。我从Python:身份验证凭据异常:“0”;请求具有无效的身份验证凭据。预期OAuth 2访问令牌“;,python,google-sheets,Python,Google Sheets,我编写了一个函数,它可以获取凭据并连接到google工作表。我从googlesheet检索数据,一切正常。出于某种原因,有时它会给我一个错误。我搜索了一下,发现有一种方法可以解决这个问题,我在下面修改了代码。但还是一样的问题。有人能帮我吗 这是我的代码: scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive'] credentials=ServiceAccoun
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"
}
}
好了,伙计们,我找到答案了。我只是在这里发布,也许将来有人会需要这个。所有课程都教授打开谷歌电子表格,然后授权您的凭证,但当您请求谷歌工作表时,关键就在这里。您的代币发生了更改,这就是为什么在您的凭证之后请求数据输入“打开”命令的原因。我把正确的答案放在这里,我试过了,效果很好 我以前的代码
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小时内获得令牌,因此您必须再次运行:
credentials=ServiceAccountCredentials.from_json_keyfile_name ('xxxx.json' , scope)
gs_client = gspread.authorize(credentials)
或者您也可以尝试:gc.login()