如何使用 google-api-python-client 保留 YouTube 数据 API V3 身份验证以供个人使用?

问题描述 投票:0回答:1

我正在开发一个项目,使用 YouTube 数据 API v3 和 google-api-python-client 以编程方式将视频上传到 YouTube。该代码仅供个人使用。

这是我目前处理身份验证的方式:

# imports
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build

flow = InstalledAppFlow.from_client_secrets_file(
    'client_secrets.json',
    scopes=['https://www.googleapis.com/auth/youtube.upload']
)

credentials = flow.run_local_server(port=8080)

youtube = build("youtube", "v3", credentials=credentials)
# code to upload the video

代码按预期工作,但我面临的问题是每次运行脚本时,它都会打开一个浏览器窗口,我必须在其中登录进行身份验证。这对我来说不太方便,因为我希望这是一个自动化过程。

最初,我尝试使用 API 密钥进行身份验证,但收到了 401 错误,并显示以下消息:

API keys are not supported by this API. Expected OAuth2 access token or other authentication credentials that assert a principal. See Cloud Docs on Authentication

我已经查看了文档,但在不经历完整的发布过程的情况下,我对哪种身份验证方法适合我的需求有点困惑。

有人可以指导我如何保持身份验证,这样我就不必每次脚本运行时都手动登录吗?任何帮助将不胜感激。

谢谢!

youtube-api youtube-data-api
1个回答
0
投票

这是我的视频插入示例,看看它是否有帮助刷新令牌存储在 token.json 中

#   To install the Google client library for Python, run the following command:
#   pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib

from __future__ import print_function

import os.path

import google.auth.exceptions
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
from googleapiclient.http import MediaFileUpload

# If modifying these scopes, delete the file token.json.
SCOPES = ['https://www.googleapis.com/auth/youtube']

def main():

    """Shows basic usage of the YouTube v3 API.
    Uploads a private video to YouTube
    """
    creds = None
    # The file token.json stores the user's access and refresh tokens, and is
    # created automatically when the authorization flow completes for the first
    # time.
    if os.path.exists('token.json'):
        try:
            creds = Credentials.from_authorized_user_file('token.json', SCOPES)
            creds.refresh(Request())
        except google.auth.exceptions.RefreshError as error:
            # if refresh token fails, reset creds to none.
            #creds = None
            print(f'An error occurred: {error}')
    # If there are no (valid) credentials available, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'C:\YouTube\dev\credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open('token.json', 'w') as token:
            token.write(creds.to_json())

    try:
        service = build('youtube', 'v3', credentials=creds)

        body = dict(
            snippet=dict(
                title="Test",
                description="test",
                tags="tes"
            ),
            status=dict(
                privacyStatus="private"
            )
        )

        media = MediaFileUpload("dummyvideo.mkv", chunksize=-1, resumable=True)

        results = service.videos().insert(
                part=",".join(body.keys()),
                body=body,
                media_body=media).execute()
        print(F'video ID: {results.get("id")}')

    except HttpError as error:
        # TODO(developer) - Handle errors from drive API.
        print(f'An error occurred: {error}')

if __name__ == '__main__':
    main()
© www.soinside.com 2019 - 2024. All rights reserved.