在 pPython 中从服务器上传 YouTube 视频 [已关闭]

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

我正在尝试使用 YouTube API v3 从服务器上传视频(我无法访问浏览器)。 我在 Stack Overflow 和其他论坛上搜索了几个小时,但没有找到明确的答案。 似乎你可以用令牌来做到这一点,但我不知道如何将其实现到脚本中。

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

YouTube 数据 api 不支持除 Oauth2 之外的任何其他身份验证。

这意味着您需要打开浏览器并同意授权。

您可以做的是授权应用程序将刷新令牌本地存储在 token.json 中,然后将其与代码一起上传到您的服务器。如果配置正确,代码可以在需要将视频上传到 api 时使用 token.json 文件中的刷新令牌来请求新的访问令牌。

我的样品

def main():

    """Shows basic usage of the YouTube v3 API.
    Prints the names and ids of the first 10 files the user has access to.
    """
    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)

        # Call the YouTube v3 API
        results = service.videos().list(
            part='snippet',
            chart='mostPopular',
            fields="nextPageToken, items").execute()
        items = results.get('items', [])


        if not items:
            print('No videos found.')
            return
        print('Videos:')
        for item in items:
            print(u'{0} ({1})'.format(item['id'], item['snippet']['title']))
    except HttpError as error:
        # TODO(developer) - Handle errors from drive API.
        print(f'An error occurred: {error}')
© www.soinside.com 2019 - 2024. All rights reserved.