我有一个Python应用程序访问Youtube-Data-API v3。
程序运行一个小时后,会抛出一个错误,提示访问令牌已过期。
怎样才能使令牌持续更长的时间?
发布于 2020-05-28 18:32:28
现在有办法延长access token的时间。一小时后就过期了。使用令牌的唯一方法是使用api提供的refresh_token获得一个新的令牌。
首先,通过在对用户进行身份验证时将access_type设置为offine来获得脱机令牌。
{
'response_type': 'code',
'client_id': 'client_id',
'redirect_uri': '...',
'access_type':'offline',
'scope': 'https://www.googleapis.com/auth/youtube.readonly',
}您将获得refresh_token、access_token、id_token以及expiry和其他一些字段,您可以将这些字段保存在数据库中,并在需要时进行提取。
在使用access_token之前,检查它是否有效。
creds = google.oauth2.credentials.Credentials(access_token,refresh_token=refresh_token,id_token=id_token,token_uri=token_uri,client_id=client_id,client_secret=client_secret,scopes=scopes,expiry=expirytime)
if creds.valid == False:
// Refresh to get the new token
req =google.auth.transport.requests.Request()
creds.refresh(req)
// Now Save new Credentials from "creds" so that you can use later.在验证access_token之后,您现在可以查询youtube data api请求了
youtube = googleapiclient.discovery.build(
"youtube", "v3",credentials=creds)
req = youtube.videos().getRating(id="xxxxxxxxx")
resp =req.execute()发布于 2020-05-28 17:43:15
当您创建O-Auth2凭据时,您需要选择"Web“,这正是我认为您正在尝试创建的。(一个网站,对吗?)
“桌面应用程序”选项是为了如果你想做一个桌面应用程序,而不是一个网站。
桌面应用程序和web应用程序处理重定向uris的方式不同,这就是导致问题的原因。
https://stackoverflow.com/questions/62071059
复制相似问题