我如何直接从我的服务器上传视频到YouTube? [英] How do I upload a video to Youtube directly from my server?

查看:605
本文介绍了我如何直接从我的服务器上传视频到YouTube?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我设置了​​一个(无头)的Web服务器,可以让人们建立自己的自定义时间推移电影。

有几个人要上传的时间推移录像他们让到YouTube。
而不是视频下载到个人的笔记本电脑,
而那个人手动将其上传到YouTube,
有没有办法我可以写我的Web服务器上的一些软件,以我的Web服务器上的视频文件,直接上传到该用户的帐户在YouTube上?

我已经告诉问我的用户提供他们的YouTube手柄和密码是错误的做法,我应该使用YouTube API V3使用OAuth。

我试过在列出的技术
<一个href=\"http://stackoverflow.com/questions/14683240/i-want-to-upload-a-video-from-my-web-page-to-youtube-by-using-javascript-youtube\">I希望通过使用JavaScript API的YouTube 上传从我的网页到YouTube的视频,
这似乎为工作,但每次我有时间来下载视频到个人的笔记本电脑,然后从笔记本电脑到YouTube上载。有没有一种方法来调整该系统直接从我的服务器到YouTube上传?

我发现了一些蟒蛇code,它(在设置我的client_secrets.json)让我直接从我的服务器的之后的那个人做了OAuth认证视频直接上传至某人的YouTube帐户。
但是,第一次了一些新的人尝试将视频上传到一些新的YouTube帐户,我的服务器从来没有处理过,它要么
(一)我的持久性有机污染物的服务器上打开Web浏览器,然后如果我的VNC服务器并输入一个YouTube的处理和密码到该网页浏览器,它就会被验证 - 但我宁愿这样做,为每一位用户。
(b)与--noauth_local_webserver选项,吐出来的命令行,并等待一个URL。然后,如果我手动复制网址并将其粘贴到网页浏览器,登录到YouTube,复制和粘贴标记回到这个应用程序,它仍然在等待输入命令行上,这个人通过认证。但我宁愿这样做,为每一位用户。我想这将是美好的,如果我能捕捉到的网址在我的cgi-bin脚本,并坚持在一个网页,然后再以某种方式获取认证响应,并填满它放回这一方案,但如何?我甚至不看这个code的打印语句或声明的raw_input

 #!的/ usr / bin中/蟒蛇
#https://developers.google.com/youtube/v3/$c$c_samples/python#upload_a_video
#这等同于在code样品
#https://developers.google.com/youtube/v3/docs/videos/insert给出import httplib
导入的httplib2
进口OS
进口随机
进口SYS
进口时间从apiclient.discovery进口构建
从apiclient.errors导入HTTPError这样的
从apiclient.http进口MediaFileUpload
从oauth2client.client进口flow_from_clientsecrets
从oauth2client.file进口仓储
从oauth2client.tools导入argparser,run_flow
#明确地告诉潜在的HTTP传输库不重试,因为
#我们正在处理的重试逻辑自己。
httplib2.RETRIES = 1次#最大数量放弃之前重试。
MAX_RETRIES = 10当这些异常复活#始终重试。
RETRIABLE_EXCEPTIONS =(httplib2.HttpLib2Error,IO错误,httplib.NotConnected,
  httplib.IncompleteRead,httplib.ImproperConnectionState,
  httplib.CannotSendRequest,httplib.CannotSendHeader,
  httplib.ResponseNotReady,httplib.BadStatusLine)#总是重试时,与这些状态之一的apiclient.errors.HttpError
#codeS上升。
RETRIABLE_STATUS_ codeS = [500,502,503,504]#在CLIENT_SECRETS_FILE变量指定一个包含文件的文件名
#OAuth 2.0已此信息,应用程序,包括它的CLIENT_ID和
#client_secret。你可以收购一个OAuth 2.0客户端ID和客户端密钥
#谷歌的开发者控制台在
#https://console.developers.google.com/。
#请确保您已启用为您的项目YouTube数据API。
#有关使用的OAuth2访问YouTube数据API的更多信息,请参见:
#https://developers.google.com/youtube/v3/guides/authentication
#有关的client_secrets.json文件格式的详细信息,请参阅:
#https://developers.google.com/api-client-library/python/guide/aaa_client_secrets
CLIENT_SECRETS_FILE =的client_secrets.json#这OAuth 2.0用户访问范围允许应用程序文件上传到
#验证用户的YouTube频道,但不允许其他类型的访问。
YOUTUBE_UPLOAD_SCOPE =htt​​ps://www.googleapis.com/auth/youtube.upload
YOUTUBE_API_SERVICE_NAME =YouTube的视频
YOUTUBE_API_VERSION =V3#该变量定义要显示的消息,如果CLIENT_SECRETS_FILE是
# 失踪。
MISSING_CLIENT_SECRETS_MESSAGE =
警告:请配置的OAuth 2.0为了使这个样本来看,你将需要填充client_secrets.json档案
在发现:   %S从开发者控制台的信息
https://console.developers.google.com/有关的client_secrets.json文件格式的详细信息,请访问:
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))VALID_PRIVACY_STATUSES =(公,私,不公开)
高清get_authenticated_service(参数):
  流量= flow_from_clientsecrets(CLIENT_SECRETS_FILE,
    范围= YOUTUBE_UPLOAD_SCOPE,
    消息= MISSING_CLIENT_SECRETS_MESSAGE)  存储=存储(%S-oauth2.json%sys.argv中[0])
  凭据= storage.get()  如果凭据是无或credentials.invalid:
    凭据= run_flow(流量,存储,参数)  返回版本(YOUTUBE_API_SERVICE_NAME,YOUTUBE_API_VERSION,
    HTTP = credentials.authorize(的httplib2.Http()))高清initialize_upload(YouTube上,选项):
  标签=无
  如果options.keywords:
    标记= options.keywords.split(,)  体=快译通(
    片段=快译通(
      标题= options.title,
      说明= options.description,
      标签=标签,
      的categoryId = options.category
    )
    状态=快译通(
      privacyStatus = options.privacyStatus
    )
  )  #调用API的videos.insert方法来创建和上传视频。
  insert_request = youtube.videos()。插入(
    部分=,加盟(body.keys()),
    身体=身体,
    #该块大小参数指定数据的每个块的大小,在
    #字节,将在一个时间上载。设定为更高的值
    #作为大块少可靠的连接带来更快的上传。设置较低
    在不太可靠的连接,更好的恢复#值。
    #
    #设定块大小等于在code键-1以下意味着整个
    #文件将在一个HTTP请求上传。 (如果上传失败,
    #仍然会重试它离开的地方。)这通常是一个最好的
    #的做法,但如果你使用Python年龄大于2.6,或者如果你是
    #App Engine上运行,则应将块大小设置为像
    #1024 * 1024(1兆字节)。
    media_body = MediaFileUpload(options.file,块大小= -1,可恢复= TRUE)
  )  resumable_upload(insert_request)#此方法实现了指数退避策略,以恢复
#上传失败。
高清resumable_upload(insert_request):
  响应=无
  错误=无
  重试= 0
  而响应无:
    尝试:
      打印上载文件...
      状态,响应= insert_request.next_chunk()
      如果响应ID:
        打印视频ID'%s'是上传成功。 %回应['身份证']
      其他:
        退出(以下简称上传失败,意外的响应:%的%响应)
    除了HTTPError这样,E:
      如果e.resp.status在RETRIABLE_STATUS_ codeS:
        错误=A retriable HTTP发生错误%d:\\ N%的%(e.resp.status,
                                                             e.content)
      其他:
        提高
    除了RETRIABLE_EXCEPTIONS,E:
      错误=发生retriable错误:%s%E    如果错误是不无:
      打印错误
      重试+ = 1
      如果重试&GT; MAX_RETRIES:
        退出(不再试图重试。)      max_sleep = 2 **重试
      sleep_seconds = random.random()* max_sleep
      打印睡%F秒,然后重试...%sleep_seconds
      time.sleep(sleep_seconds)如果__name__ =='__main__':
  argparser.add_argument( - 文件,要求= TRUE,帮助=视频文件上传)
  argparser.add_argument( - 题,帮助=视频标题,默认值=测试题)
  argparser.add_argument( - 描述,帮助=视频描述,
    默认值为考试说明)
  argparser.add_argument( - 类别,默认值为22,
    帮助=数字视频类别。+
      见https://developers.google.com/youtube/v3/docs/videoCategories/list)
  argparser.add_argument( - 关键字,帮助=视频的关键字,以逗号分隔
    默认值=)
  argparser.add_argument( - privacyStatus,选择= VALID_PRIVACY_STATUSES,
    默认值= VALID_PRIVACY_STATUSES [0],帮助=视频隐私状态。)
  ARGS = argparser.parse_args()  如果不是os.path.exists(args.file):
    退出(请使用--file =参数指定一个有效的文件。)  YouTube的= get_authenticated_service(参数)
  尝试:
    initialize_upload(YouTube上,参数)
  除了HTTPError这样,E:
    打印HTTP错误%d个出现了:\\ N%的%(e.resp.status,e.content)


解决方案

非常有用的一步一步的指导关于如何访问和新鲜的标记和保存以供使用YouTube的OAuth API V3将来使用。 PHP服务器端的YouTube V3 OAuth的API视频上传指南。
https://www.domsammut.com/$c$c/php-server-side-youtube-v3-oauth-api-video-upload-guide

I'm setting up a (headless) web server that lets people build their own custom time-lapse movies.

Several people want to upload the time-lapse videos they make to YouTube. Rather than download the video to that person's laptop, and the that person manually uploads it to YouTube, is there a way I can write some software on my web server to take that video file on my web server and upload it directly to that user's account on YouTube?

I've been told that asking my users for their YouTube handle and password is the Wrong Thing To Do, and I should be using the YouTube V3 API with Oauth.

I tried the techniques listed at " I want to upload a video from my web page to youtube by using javascript youtube API ", which seems to "work", but every time I had to download the video to that person's laptop and then uploading from the laptop to YouTube. Is there a way to tweak that system to upload directly from my server to YouTube?

I found some python code that (after I set up my client_secrets.json) lets me upload videos directly from my server directly to someone's YouTube account after that person did the Oauth authentication. But the first time some new person tries to upload a video to some new YouTube account that my server has never dealt with before, it either (a) pops open a web browser on my server, and then if I VNC to the server and type in a YouTube handle and password into that web browser, it gets authenticated -- but I'd rather not do that for every user. (b) with the "--noauth_local_webserver" option, spits out a URL on the command line and waits. Then if I manually copy that URL and paste it into a web browser, log in to YouTube, copy-and-paste the token back into this application that is still waiting for input on the command line, that person gets authenticated. But I'd rather not do that for every user. I guess that would be OK if I could capture that URL in my cgi-bin script and stick it in a web page, and then later somehow get the authentication response and cram it back into this program, but how? I don't even see that print statement or the raw_input statement in this code.

#!/usr/bin/python
#   https://developers.google.com/youtube/v3/code_samples/python#upload_a_video
# which is identical to the code sample at
#   https://developers.google.com/youtube/v3/docs/videos/insert

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.client import flow_from_clientsecrets
from oauth2client.file import Storage
from oauth2client.tools import argparser, run_flow


# 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]

# The CLIENT_SECRETS_FILE variable specifies the name of a file that contains
# the OAuth 2.0 information for this application, including its client_id and
# client_secret. You can acquire an OAuth 2.0 client ID and client secret from
# the Google Developers Console at
# https://console.developers.google.com/.
# Please ensure that you have enabled the YouTube Data API for your project.
# For more information about using OAuth2 to access the YouTube Data API, see:
#   https://developers.google.com/youtube/v3/guides/authentication
# For more information about the client_secrets.json file format, see:
#   https://developers.google.com/api-client-library/python/guide/aaa_client_secrets
CLIENT_SECRETS_FILE = "client_secrets.json"

# This OAuth 2.0 access scope allows an application to upload files to the
# authenticated user's YouTube channel, but doesn't allow other types of access.
YOUTUBE_UPLOAD_SCOPE = "https://www.googleapis.com/auth/youtube.upload"
YOUTUBE_API_SERVICE_NAME = "youtube"
YOUTUBE_API_VERSION = "v3"

# This variable defines a 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 Developers Console
https://console.developers.google.com/

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))

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


def get_authenticated_service(args):
  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(flow, storage, args)

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

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

  body=dict(
    snippet=dict(
      title=options.title,
      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.
  insert_request = youtube.videos().insert(
    part=",".join(body.keys()),
    body=body,
    # The chunksize parameter specifies the size of each chunk of data, in
    # bytes, that will be uploaded at a time. Set a higher value for
    # reliable connections as fewer chunks lead to faster uploads. Set a lower
    # value for better recovery on less reliable connections.
    #
    # Setting "chunksize" equal to -1 in the code below 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(options.file, chunksize=-1, resumable=True)
  )

  resumable_upload(insert_request)

# This method implements an exponential backoff strategy to resume a
# failed upload.
def resumable_upload(insert_request):
  response = None
  error = None
  retry = 0
  while response is None:
    try:
      print "Uploading file..."
      status, response = insert_request.next_chunk()
      if 'id' in response:
        print "Video id '%s' was successfully uploaded." % 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)

if __name__ == '__main__':
  argparser.add_argument("--file", required=True, help="Video file to upload")
  argparser.add_argument("--title", help="Video title", default="Test Title")
  argparser.add_argument("--description", help="Video description",
    default="Test Description")
  argparser.add_argument("--category", default="22",
    help="Numeric video category. " +
      "See https://developers.google.com/youtube/v3/docs/videoCategories/list")
  argparser.add_argument("--keywords", help="Video keywords, comma separated",
    default="")
  argparser.add_argument("--privacyStatus", choices=VALID_PRIVACY_STATUSES,
    default=VALID_PRIVACY_STATUSES[0], help="Video privacy status.")
  args = argparser.parse_args()

  if not os.path.exists(args.file):
    exit("Please specify a valid file using the --file= parameter.")

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

解决方案

Very useful step-by-step guide about how to get access and fresh tokens and save them for future use using YouTube OAuth API v3. PHP server-side YouTube V3 OAuth API video upload guide. https://www.domsammut.com/code/php-server-side-youtube-v3-oauth-api-video-upload-guide

这篇关于我如何直接从我的服务器上传视频到YouTube?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆