如何在youtube python api中使用refresh_token?

时间:2016-09-28 15:07:02

标签: python youtube-api google-api-client

所以我以这种方式获得了刷新令牌,我可以保留吗?

如果是这样,我下次如何使用它,以便我不需要打开浏览器?

现在我正在考虑直接创建OAuth2Credentials对象,这是正确的方法吗?

from urllib.parse import urlparse, parse_qs
from oauth2client.client import flow_from_clientsecrets, OAuth2Credentials
from oauth2client.file import Storage
from oauth2client.tools import argparser, run_flow
from apiclient.discovery import build
from apiclient.errors import HttpError
from oauth2client.contrib import gce
import httplib2
import webbrowser

CLIENT_SECRETS_FILE = "bot_credentials.json"
flow = client.flow_from_clientsecrets(
     CLIENT_SECRETS_FILE,
    scope=scope,
redirect_uri='http://127.0.0.1:65010')
flow.params['include_granted_scopes'] = 'true'
flow.params['access_type'] = 'offline'
auth_uri = flow.step1_get_authorize_url()
webbrowser.open(auth_uri)
url = input('Please enter the redirected url with code')
code = get_url_param(url, 'code')
if code is None:
    print('there is an error in your redirect link with code parameter, check if it exists')
    exit()
print(code)
credentials = flow.step2_exchange(code[0])
print(credentials.to_json())#refresh_token here!!!

1 个答案:

答案 0 :(得分:0)

如果用户同意授权您的应用访问这些资源,Google会向您的应用返回一个令牌。根据您的应用程序的类型,它将验证令牌或将其交换为不同类型的令牌。请检查此documentation

  

例如,服务器端Web应用程序将交换返回的令牌以获取访问令牌和刷新令牌。访问令牌将允许应用程序代表用户授权请求,并且刷新令牌将允许应用程序在原始访问令牌过期时检索新的访问令牌。

基本上,如果您的应用程序在授权过程中获得刷新令牌,那么您将需要定期使用该令牌来获取新的有效访问令牌。服务器端Web应用程序,已安装的应用程序和设备都获得刷新令牌。

我们声明here您的应用程序可以随时向Google的授权服务器发送POST请求,指定您的客户端ID,客户端密码和刷新令牌为用户。该请求还应将grant_type参数值设置为refresh_token

  

以下示例演示了此请求:

POST /o/oauth2/token HTTP/1.1
Host: accounts.google.com
Content-Type: application/x-www-form-urlencoded

client_id=21302922996.apps.googleusercontent.com&
client_secret=XTHhXh1SlUNgvyWGwDk1EjXB&
refresh_token=1/6BMfW9j53gdGImsixUH6kU5RsR4zwI9lUVX-tqf8JXQ&
grant_type=refresh_token
     

授权服务器将返回包含新访问令牌的JSON对象:

{
  "access_token":"1/fFAGRNJru1FTz70BzhT3Zg",
  "expires_in":3920,
  "token_type":"Bearer"
}

您可以查看此sample on GitHub以生成YouTube API的刷新令牌。请注意,这也将创建一个名为generate_token.py-oauth的文件,其中包含此信息。