通过 Youtube 上传,通过 api 设置为私有(锁定)

Posted

技术标签:

【中文标题】通过 Youtube 上传,通过 api 设置为私有(锁定)【英文标题】:Upload via the Youtube via api set to Private (locked) 【发布时间】:2021-02-18 01:09:20 【问题描述】:

我一直在使用youtube API远程上传。但是,由于条款和政策,在修改代码一段时间后,所有上传的视频都会“私人(锁定)”。由于“无法上诉此违规行为”,我也无法上诉。只是为了澄清一下,我之前可以上传,但最近才开始收到此错误。

代码: youtube-上传者

#!/usr/bin/python

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

import google.oauth2.credentials
import google_auth_oauthlib.flow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
from googleapiclient.http import MediaFileUpload
from google_auth_oauthlib.flow import InstalledAppFlow

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


# 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, http.client.NotConnected,
  http.client.IncompleteRead, http.client.ImproperConnectionState,
  http.client.CannotSendRequest, http.client.CannotSendHeader,
  http.client.ResponseNotReady, http.client.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'

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

VALID_PRIVACY_STATUSES = ('public', 'private', 'unlisted')



def get_authenticated_service(): # Modified
    credential_path = os.path.join('./', '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)
    return build(API_SERVICE_NAME, API_VERSION, credentials=credentials)

def initialize_upload(youtube, options):
  tags = None
  if options.keywords:
    tags = options.keywords.split(',')

  body=dict(
    snippet=dict(
      title=options.getFileName("video").split(".", 1)[0],
      description=options.description,
      tags=tags,
      categoryId=options.category
    ),
    status=dict(
      privacyStatus=options.privacyStatus
    )
  )

  # Call the API's videos.insert method to create and upload the video.
  videoPath = "/Users\caspe\OneDrive\Documents\Övrigt\Kodning\AwsCSGO\Video\%s" % (options.getFileName("video"))
  insert_request = youtube.videos().insert(
    part=','.join(body.keys()),
    body=body,
    media_body=MediaFileUpload(videoPath, chunksize=-1, resumable=True)
  )

  resumable_upload(insert_request, options)

# This method implements an exponential backoff strategy to resume a
# failed upload.
def resumable_upload(request, options):
  response = None
  error = None
  retry = 0
  while response is None:
    try:
      print('Uploading file...')
      status, response = request.next_chunk()
      if response is not None:
        if 'id' in response:
          print ('The video with the id %s was successfully uploaded!' % response['id'])
          
          # upload thumbnail for Video
          options.insertThumbnail(youtube, response['id'])
        else:
          exit('The upload failed with an unexpected response: %s' % response)
    except HttpError as 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 as 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)

if __name__ == '__main__':
  args = videoDetails.Video()
  youtube = get_authenticated_service()

  try:
    initialize_upload(youtube, args)
  except HttpError as e:
    print ('An HTTP error %d occurred:\n%s') % (e.resp.status, e.content)

视频详情

import os
from googleapiclient.http import MediaFileUpload

class Video:
    description = "test description"
    category = "22"
    keywords = "test"
    privacyStatus = "public"

    def getFileName(self, type):
        for file in os.listdir("/Users\caspe\OneDrive\Documents\Övrigt\Kodning\AwsCSGO\Video"):
            if type == "video" and file.split(".", 1)[1] != "jpg":
                return file
                break
            elif type == "thumbnail" and file.split(".", 1)[1] != "mp4":
                return file
                break

    def insertThumbnail(self, youtube, videoId):
        thumnailPath = "/Users\caspe\OneDrive\Documents\Övrigt\Kodning\AwsCSGO\Video\%s" % (self.getFileName("thumbnail"))

        request = youtube.thumbnails().set(
            videoId=videoId,
            media_body=MediaFileUpload(thumnailPath)
        )
        response = request.execute()
        print(response)

【问题讨论】:

所以,你可以上传,但只是它变成了私人的? 是的,添加了一张图片来清除 【参考方案1】:

如果您查看Video.insert 的文档,您会在页面顶部找到以下内容。这是最近开始实施的一项新政策。

在您的申请通过验证之前,您上传的所有视频都将设为私有。您需要先通过审核,然后才能上传公开视频。

请注意,一旦您的应用程序通过验证,这不会自动将所有现有的先前上传的视频设置为公开,您需要自己做。

【讨论】:

好的,谢谢,有点奇怪,因为我已经能够上传 20 多个视频,但最近才收到错误。 似乎这项新政策的实施并未立即在全球范围内推广,它似乎是某种缓慢的推广。 ffs ok.... 非常感谢您的回答 :) 让我们进行审核

以上是关于通过 Youtube 上传,通过 api 设置为私有(锁定)的主要内容,如果未能解决你的问题,请参考以下文章

YouTube 频道中的“已发布视频”和“上传”有啥区别?以及如何通过 YouTube Data v3 API 获取它们?

允许通过 API v3 访问 Google 服务帐户 YouTube 上传访问权限

PHP:使用同步标志上传 YouTube v3 API 字幕

无法通过 Google Apps 脚本中的 YouTube 数据 API 从云端硬盘上传:空响应

无法通过 Google Apps 脚本中的 YouTube 数据 API 从云端硬盘上传:空响应

每天通过youtube api发送视频的限制