如何为 youtube python api 使用 refresh_token?

use*_*ty1 5 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!!!
Run Code Online (Sandbox Code Playgroud)

abi*_*ita 0

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

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

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

这里指出,您的应用程序可以随时向 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
Run Code Online (Sandbox Code Playgroud)

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

{
  "access_token":"1/fFAGRNJru1FTz70BzhT3Zg",
  "expires_in":3920,
  "token_type":"Bearer"
}
Run Code Online (Sandbox Code Playgroud)

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