首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在Python桌面应用程序中持久化Youtube数据API访问令牌

在Python桌面应用程序中持久化Youtube数据API访问令牌
EN

Stack Overflow用户
提问于 2020-05-28 17:39:31
回答 2查看 427关注 0票数 0

我有一个Python应用程序访问Youtube-Data-API v3。

程序运行一个小时后,会抛出一个错误,提示访问令牌已过期。

怎样才能使令牌持续更长的时间?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-05-28 18:32:28

现在有办法延长access token的时间。一小时后就过期了。使用令牌的唯一方法是使用api提供的refresh_token获得一个新的令牌。

首先,通过在对用户进行身份验证时将access_type设置为offine来获得脱机令牌。

代码语言:javascript
复制
{
    'response_type': 'code',
    'client_id': 'client_id',
    'redirect_uri': '...',
    'access_type':'offline',
    'scope': 'https://www.googleapis.com/auth/youtube.readonly',
}

您将获得refresh_tokenaccess_tokenid_token以及expiry和其他一些字段,您可以将这些字段保存在数据库中,并在需要时进行提取。

在使用access_token之前,检查它是否有效。

代码语言:javascript
复制
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请求了

代码语言:javascript
复制
youtube = googleapiclient.discovery.build(
    "youtube", "v3",credentials=creds)
req = youtube.videos().getRating(id="xxxxxxxxx")
resp =req.execute()
票数 0
EN

Stack Overflow用户

发布于 2020-05-28 17:43:15

当您创建O-Auth2凭据时,您需要选择"Web“,这正是我认为您正在尝试创建的。(一个网站,对吗?)

“桌面应用程序”选项是为了如果你想做一个桌面应用程序,而不是一个网站。

桌面应用程序和web应用程序处理重定向uris的方式不同,这就是导致问题的原因。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62071059

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档