【问题标题】:Python youtube API oauth2client invalid_grant after a while一段时间后,Python youtube API oauth2client invalid_grant
【发布时间】:2022-01-10 14:01:53
【问题描述】:

我有一个机器人,它每 24 小时使用 Youtube API 上传一个 Youtube 视频。我查看了https://github.com/SteBurz/youtube-uploader 的示例(这只是用 Python 3 重写的https://developers.google.com/youtube/v3/guides/uploading_a_video),但是大约一周后,当我尝试上传视频时,它给了我invalid_grant

这是“构建”API 的代码部分。我尝试使用refresh 方法,但这似乎不是答案。

import http.client
import httplib2
import os
import random
import time

from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
from googleapiclient.http import MediaFileUpload

from oauth2client import client
from oauth2client import tools
from oauth2client.file import Storage

# References:
# https://developers.google.com/youtube/v3/guides/uploading_a_video
# https://github.com/SteBurz/youtube-uploader

CLIENT_SECRETS_FILE = os.path.join(
    os.path.abspath(os.path.dirname(__file__)),
    "..",
    "credentials-youtube.json"
)

SCOPES = [
    'https://www.googleapis.com/auth/youtube.upload',
    'https://www.googleapis.com/auth/youtube.force-ssl',
]
API_SERVICE_NAME = 'youtube'
API_VERSION = 'v3'

def get_authenticated_service():
        credential_path = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'credentials.json')
        store = Storage(credential_path)
        credentials = store.get()
        if not credentials or credentials.invalid:
                flow = client.flow_from_clientsecrets(CLIENT_SECRETS_FILE, SCOPES)
                credentials = tools.run_flow(flow, store)
        else:
            credentials.refresh(httplib2.Http())
        return build(API_SERVICE_NAME, API_VERSION, credentials=credentials)

【问题讨论】:

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


    【解决方案1】:

    invalid_grant 错误对于很多事情来说都是一个包罗万象的错误。当前 invalid_grant 通常意味着您的刷新令牌已过期。

    为外部用户类型配置了 OAuth 同意屏幕且发布状态为“正在测试”的 Google Cloud Platform 项目发出了一个在 7 天后到期的刷新令牌。

    诀窍是转到 Google 云控制台并将您的项目设置为生产,然后您的刷新令牌将持续超过 7 天

    至于您的代码,您需要获取它以请求新的访问令牌,因为您拥有的那个已不再工作。所以删除存储中的所有内容

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-28
      • 2018-07-02
      • 2021-10-15
      • 2020-05-02
      • 2015-07-14
      • 1970-01-01
      相关资源
      最近更新 更多