使用 Python 中的 YouTube Data API v3 将视频上传到 YouTube 并将其添加到播放列表

2024-05-22

我编写了一个脚本,在 python 中使用 YouTube Data API v3 将视频上传到 YouTube,并借助中给出的示例示例代码 https://developers.google.com/youtube/v3/guides/uploading_a_video.

我编写了另一个脚本,使用相同的 YouTube Data API v3 将上传的视频添加到播放列表,您可以看到here https://github.com/alokmahor/add_to_youtube_playlist/blob/master/playlist.py

之后,我编写了一个脚本来上传视频并将该视频添加到播放列表。在我负责身份验证和范围的情况下,我仍然收到权限错误。这是我的新脚本

#!/usr/bin/python

import httplib
import httplib2
import os
import random
import sys
import time

from apiclient.discovery import build
from apiclient.errors import HttpError
from apiclient.http import MediaFileUpload
from oauth2client.file import Storage
from oauth2client.client import flow_from_clientsecrets
from oauth2client.tools import run

# Explicitly tell the underlying HTTP transport library not to retry, since
# we are handling retry logic ourselves.
httplib2.RETRIES = 1

# Maximum number of times to retry before giving up.
MAX_RETRIES = 10

# Always retry when these exceptions are raised.
RETRIABLE_EXCEPTIONS = (httplib2.HttpLib2Error, IOError, httplib.NotConnected,
  httplib.IncompleteRead, httplib.ImproperConnectionState,
  httplib.CannotSendRequest, httplib.CannotSendHeader,
  httplib.ResponseNotReady, httplib.BadStatusLine)

# Always retry when an apiclient.errors.HttpError with one of these status
# codes is raised.
RETRIABLE_STATUS_CODES = [500, 502, 503, 504]
CLIENT_SECRETS_FILE = "client_secrets.json"

# A limited OAuth 2 access scope that allows for uploading files, but not other
# types of account access.
YOUTUBE_UPLOAD_SCOPE = "https://www.googleapis.com/auth/youtube.upload"
YOUTUBE_API_SERVICE_NAME = "youtube"
YOUTUBE_API_VERSION = "v3"

# Helpful message to display if the CLIENT_SECRETS_FILE is missing.
MISSING_CLIENT_SECRETS_MESSAGE = """
WARNING: Please configure OAuth 2.0

To make this sample run you will need to populate the client_secrets.json file
found at:

   %s

with information from the APIs Console
https://code.google.com/apis/console#access

For more information about the client_secrets.json file format, please visit:
https://developers.google.com/api-client-library/python/guide/aaa_client_secrets
""" % os.path.abspath(os.path.join(os.path.dirname(__file__),
                                   CLIENT_SECRETS_FILE))

def get_authenticated_service():
  flow = flow_from_clientsecrets(CLIENT_SECRETS_FILE, scope=YOUTUBE_UPLOAD_SCOPE,
    message=MISSING_CLIENT_SECRETS_MESSAGE)

  storage = Storage("%s-oauth2.json" % sys.argv[0])
  credentials = storage.get()

  if credentials is None or credentials.invalid:
    credentials = run(flow, storage)

  return build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION,
    http=credentials.authorize(httplib2.Http()))


def initialize_upload(title,description,keywords,privacyStatus,file):
  youtube = get_authenticated_service()

  tags = None
  if keywords:
    tags = keywords.split(",")

  insert_request = youtube.videos().insert(
    part="snippet,status",
    body=dict(
      snippet=dict(
        title=title,
        description=description,
        tags=tags,
        categoryId='26'
      ),
      status=dict(
        privacyStatus=privacyStatus
      )
    ),
    # chunksize=-1 means that the entire file will be uploaded in a single
    # HTTP request. (If the upload fails, it will still be retried where it
    # left off.) This is usually a best practice, but if you're using Python
    # older than 2.6 or if you're running on App Engine, you should set the
    # chunksize to something like 1024 * 1024 (1 megabyte).
    media_body=MediaFileUpload(file, chunksize=-1, resumable=True)
  )

  vid=resumable_upload(insert_request)

  #Here I added lines to add video to playlist
  #add_video_to_playlist(youtube,vid,"PL2JW1S4IMwYubm06iDKfDsmWVB-J8funQ")
  #youtube = get_authenticated_service()
  add_video_request=youtube.playlistItems().insert(
        part="snippet",
        body={
                'snippet': {
                  'playlistId': "PL2JW1S4IMwYubm06iDKfDsmWVB-J8funQ", 
                  'resourceId': {
                          'kind': 'youtube#video',
                      'videoId': vid
                    }
                #'position': 0
                }
        }
    ).execute()


def resumable_upload(insert_request):
  response = None
  error = None
  retry = 0
  vid=None
  while response is None:
    try:
      print "Uploading file..."
      status, response = insert_request.next_chunk()
      if 'id' in response:
        print "'%s' (video id: %s) was successfully uploaded." % (
          title, response['id'])
    vid=response['id']
      else:
        exit("The upload failed with an unexpected response: %s" % response)
    except HttpError, e:
      if e.resp.status in RETRIABLE_STATUS_CODES:
        error = "A retriable HTTP error %d occurred:\n%s" % (e.resp.status,
                                                             e.content)
      else:
        raise
    except RETRIABLE_EXCEPTIONS, e:
      error = "A retriable error occurred: %s" % e

    if error is not None:
      print error
      retry += 1
      if retry > MAX_RETRIES:
        exit("No longer attempting to retry.")

      max_sleep = 2 ** retry
      sleep_seconds = random.random() * max_sleep
      print "Sleeping %f seconds and then retrying..." % sleep_seconds
      time.sleep(sleep_seconds)
  return vid  

if __name__ == '__main__':

  title="sample title"
  description="sample description"

  keywords="keyword1,keyword2,keyword3"

  privacyStatus="public"
  file="myfile.mp4"
  vid=initialize_upload(title,description,keywords,privacyStatus,file)
  print 'video ID is :',vid

我不知道出了什么问题。我收到权限错误。两个脚本独立运行都很好。

谁能帮我找出我错在哪里或者如何实现上传视频并添加播放列表。


我得到的答案实际上在两个独立的脚本范围是不同的。
上传范围是“https://www.googleapis.com/auth/youtube.upload https://www.googleapis.com/auth/youtube.upload"
添加到播放列表的范围是“https://www.googleapis.com/auth/youtube https://www.googleapis.com/auth/youtube"

由于范围不同,所以我必须单独处理身份验证。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 Python 中的 YouTube Data API v3 将视频上传到 YouTube 并将其添加到播放列表 的相关文章

  • python中的“For”循环结构

    当我调试一小段代码时 我注意到一些意想不到的事情 for 循环循环遍历文件名以删除数字 通过查看字符串的每个字符并替换它 似乎打印了文件名 因为它存在于循环的第一遍中并循环遍历这些字母 所以如果像我在代码中所做的那样 对传递给循环的字符串进
  • 将字符转换为日期时间 odoo 9

    我有两个字符字段 从 odoo 中的 excel 或 csv 导入数据 time 1 fields Char string Time 1 time 2 fields Char string Time 2 result fields Floa
  • 尽管脚本是“纯”Python,但 .py 和 .ipy 文件的 IPython 行为不同(自定义异常处理程序挂钩停止工作)

    我编写了一个异常处理程序 旨在记录所有未捕获的异常 在调用普通 python 异常挂钩之前的代码中 Python 和 iPython 执行此操作的方法略有不同 我发现 iPython 这样做的方法仅在从交互式会话中运行时有效 或者当 使用
  • 如何在sqlite3中创建多个“:memory:”数据库

    我正在尝试使用 sqlite3 创建多个内存数据库 如果可能 对于磁盘数据库 我会这样做 import sqlite3 db1 sqlite3 connect mnt tmp db1 db db2 sqlite3 connect mnt t
  • Python 2.7 - statsmodels - 格式化和编写摘要输出

    我正在使用逻辑回归pandas 0 11 0 数据处理 和statsmodels 0 4 3在 Mac OSX Lion 上进行实际回归 我将运行约 2 900 个不同的逻辑回归模型 并需要将结果输出到 csv 文件并以特定方式格式化 目前
  • spacy 是否将令牌列表作为输入?

    我想使用 spacy 的 POS 标记 NER 和依存解析 而不使用单词标记化 事实上 我的输入是代表一个句子的标记列表 我想尊重用户的标记化 无论是使用 spacy 还是任何其他 NLP 包 这是否可能 现在 我使用这个基于 spacy
  • 如何在两个类之间共享数据

    Question 有没有一种方法可以让两个类同时相互继承 背景 我目前正在开发一个 Socket Server 项目 在这个项目中 我有两个课程 一个Server类 以及一个GUI班级 他们的目的是不言自明的 但是 我显然需要让两个班级相互
  • numpy.polyfit 给出有用的拟合,但协方差矩阵无限

    我正在尝试将多项式拟合到一组数据 有时可能会出现以下情况 返回的协方差矩阵numpy ployfit仅由inf 尽管拟合似乎很有用 没有numpy inf或数据中的 numpy nan Example import numpy as np
  • 现在与出生日期之间的年、月、日、分钟差异

    import datetime birthday datetime datetime 1996 8 15 differnce datetime datetime now birthday This returns a timedelta o
  • 包装一个类,其方法返回该类的实例

    我需要编写一个类来包装第三方包中的类 通常 第三方类具有返回第三方类实例的方法 这些方法的包装版本必须将这些实例转换为包装类的实例 但我无法使其工作 我正在使用 Python 2 7 和新式类 基于创建一个包装类来围绕现有函数调用前置和后置
  • Redis - 错误:值不是有效的浮点数

    我在 Redis 中有一个排序集 我试图通过在Python代码中使用zincrby来更新特定元素的计数器值 例如 conn zincrby usersSet float 1 user1 但它显示错误为 错误 值不是有效的浮点数 我在 cli
  • Ubuntu Python shebang 线不工作

    无法让 shebang 线在 Ubuntu 中为 python 脚本工作 我每次只收到命令未找到错误 test py usr bin env python print Ran which python usr bin python 在 sh
  • 如何删除Python字符串的最后一个utf8字符

    我有一个包含 utf 8 编码文本的字符串 我需要删除最后一个 utf 8 字符 到目前为止我做到了 msg msg 1 但这只会删除最后一个字节 只要最后一个字符是 ASCII 代码 它就可以工作 当最后一个字符是多字节字符时 它不再起作
  • 改变字典的哈希函数

    按照此question https stackoverflow com questions 37100390 towards understanding dictionaries 我们知道两个不同的字典 dict 1 and dict 2例
  • 无法读取未定义的属性“搜索”

    我正在尝试制作一个使用 YouTube API 的脚本 我输入了一个关键字 youtube api 找到视频 gt 脚本获取第一个结果并返回 VideoID 现在我的问题是 当我按下提交按钮时 搜索功能不会被触发 有谁知道这可能是什么原因
  • ipython/ pylab/ matplotlib安装和初始化错误

    我在 OS X El Captain 上安装了 matplotlib anaconda ipython 然而 即使在尝试以所有可能的方式设置环境变量之后 我仍无法启动 ipython shell pylab 版本 这是错误 ImportEr
  • 绘制与Fig.show()内联的IPython Notebook图形?

    我正在使用 IPython Notebook 调用内联模式 pylab inline 以下代码立即在单元格处绘制一个图形 fig plt figure axes fig add axes 0 0 1 1 不过 我想在一个单元格中创建绘图 轴
  • 如何将输入读取为数字?

    这个问题的答案是社区努力 help privileges edit community wiki 编辑现有答案以改进这篇文章 目前不接受新的答案或互动 Why are x and y下面的代码中使用字符串而不是整数 注意 在Python 2
  • Pandas Dataframe 在由索引分隔的部分中进行插值

    我的示例代码如下 import pandas as pd dictx col1 1 nan nan nan 5 nan 7 nan 9 nan nan nan 13 col2 20 nan nan nan 22 nan 25 nan 30
  • 如何检测一个二维数组是否在另一个二维数组内?

    因此 在堆栈溢出成员的帮助下 我得到了以下代码 data needle s which is a png image base64 code goes here decoded data decode base64 f cStringIO

随机推荐