首页 > 解决方案 > Youtube Video Insert 返回“默认”视频资源

问题描述

我正在尝试将视频从 S3 存储桶上传到 YouTube,并返回暗示成功发布的奇怪输出,但没有提供任何预期的回报。同样,我在我的代码中设置了title和之类的属性description,但正如您从输出中看到的那样,这实际上并没有被设置。

示例输出:

{
  "id": "-pfZ_BNH9kg",
  "snippet": {
    "channelId": "UCZ5AUe-rp3rXKeFS0yx4ZBA",
    "title": "unknown",
    "channelTitle": "Patrick Hanford",
    "publishedAt": "2020-04-30T19:22:15.000Z",
    "thumbnails": {
      "high": {
        "url": "https://i.ytimg.com/vi/-pfZ_BNH9kg/hqdefault.jpg",
        "height": 360,
        "width": 480
      },
      "default": {
        "url": "https://i.ytimg.com/vi/-pfZ_BNH9kg/default.jpg",
        "height": 90,
        "width": 120
      },
      "medium": {
        "url": "https://i.ytimg.com/vi/-pfZ_BNH9kg/mqdefault.jpg",
        "height": 180,
        "width": 320
      }
    },
    "localized": {
      "title": "unknown",
      "description": ""
    },
    "liveBroadcastContent": "none",
    "categoryId": "20",
    "description": ""
  },
  "etag": "Dn5xIderbhAnUk5TAW0qkFFir0M/3T1YGvGo1YyaTKtTpl8JrJqWS4M",
  "status": {
    "embeddable": true,
    "privacyStatus": "public",
    "uploadStatus": "uploaded",
    "publicStatsViewable": true,
    "license": "youtube"
  },
  "kind": "youtube#video"
}

上传代码:

    def post(self, attempts=None):
        TEST_VIDEO = "http://streamon-perm.s3.amazonaws.com/WPHM-48k-pl-33366.mp4"

        headers = {"Content-Type": "video/mp4"}

        upload_request_body = {
            "snippet": {
                "title": "Test Video Upload",
                "description": "This is a test of uploading videos.",
                "categoryId": "22",
            },
            "status": {
                "privacyStatus": "public"
            },
            "fileDetails": {
                "fileName": TEST_VIDEO,
                "fileType": "video"
            }
        }

        params = {
            "access_token": self.google_token.get("access_token", None),
            "id": self.google_token.get("id_token", None),
            "part": "snippet, status"
        }

        extra = {
            "client_id": self.client_id,
            "client_secret": self.client_secret
        }

        google_oauth_session = OAuth2Session(
            self.client_id,
            token=self.google_token,
            auto_refresh_url=self.token_url,
            auto_refresh_kwargs=extra,
            token_updater=self._save_token
        )

        upload_response = google_oauth_session.post(
            self.video_post_url,
            headers=headers,
            json=upload_request_body,
            params=params
        )
        logger.info("Response from VIDEO UPLOAD: %s", repr(upload_response.content))
        return True

我也尝试过从 S3 下载文件并直接与文件一起上传,我得到了相同的结果。如果没有正确的错误消息或任何要关闭的东西,我真的不确定接下来要尝试什么。任何帮助是极大的赞赏。

我也尝试过单独使用requests,而不是使用oauthlib完全相同的结果。

    def post(self, attempts=None):
        if attempts is None:
            attempts = 0
        if self.neutered:
            msg = "Youtube post() disabled by ENVIRONMENT variables."
            logger.info(msg)
            return msg
        logger.info("Youtube post() entered with attempt # %s", self.post_attempts)

        if self.google_token is None:
            self.google_token = self._set_google_token()
            attempts += 1
            self.post(attempts=attempts)

        headers = {
            "Content-Type": "video/mp4",
            "client_id": self.client_id,
            "client_secret": self.client_secret,
            "Authorization": "Bearer " + self.google_token["access_token"]
            }

        params = {
            "access_token": self.google_token.get("access_token", None),
            "id": self.google_token.get("id_token", None),
            "part": "snippet, status"
        }

        upload_request_body = {
            "snippet": {
                "title": "Test Video Upload",
                "description": "This is a test of uploading videos from POST.",
                "categoryId": "22",
            },
            "status": {
                "privacyStatus": "public"
            },
            "fileDetails": {
                "fileName": TEST_VIDEO,
                "fileType": "video"
            }
        }

        upload_response = requests.post(
            self.video_post_url,
            params=params,
            headers=headers,
            json=upload_request_body
        )
        logger.info("Response from VIDEO UPLOAD: %s", repr(upload_response.content))
        return True

标签: python-2.7youtubeyoutube-apiyoutube-data-api

解决方案


我也尝试过从 S3 下载文件并直接与文件一起上传,我得到了相同的结果。

您遇到此问题可能是因为您实际上并未发送文件。upload_request_body.fileDetails.fileName不是链接/文件的地方。它只是一个描述属性。

您是否尝试过来自https://developers.google.com/youtube/v3/code_samples/code_snippets的自动生成代码?这是你可以到达那里的:

# -*- coding: utf-8 -*-

# Sample Python code for youtube.videos.insert
# NOTES:
# 1. This sample code uploads a file and can't be executed via this interface.
#    To test this code, you must run it locally using your own API credentials.
#    See: https://developers.google.com/explorer-help/guides/code_samples#python
# 2. This example makes a simple upload request. We recommend that you consider
#    using resumable uploads instead, particularly if you are transferring large
#    files or there's a high likelihood of a network interruption or other
#    transmission failure. To learn more about resumable uploads, see:
#    https://developers.google.com/api-client-library/python/guide/media_upload

import os

import googleapiclient.discovery

from googleapiclient.http import MediaFileUpload

def main():
    # Disable OAuthlib's HTTPS verification when running locally.
    # *DO NOT* leave this option enabled in production.
    os.environ["OAUTHLIB_INSECURE_TRANSPORT"] = "1"

    api_service_name = "youtube"
    api_version = "v3"
    DEVELOPER_KEY = "YOUR_API_KEY"

    youtube = googleapiclient.discovery.build(
        api_service_name, api_version, developerKey = DEVELOPER_KEY)

    request = youtube.videos().insert(
        part="snippet,status",
        body={
          "fileDetails": {
            "fileName": "qwer",
            "fileType": "video"
          },
          "snippet": {
            "categoryId": "22",
            "description": "This is a test of uploading videos.",
            "title": "Test Video Upload"
          },
          "status": {
            "privacyStatus": "public"
          }
        },

        # TODO: For this request to work, you must replace "YOUR_FILE"
        #       with a pointer to the actual file you are uploading.
        media_body=MediaFileUpload("YOUR_FILE")
    )
    response = request.execute()

    print(response)

if __name__ == "__main__":
    main()

我相信它应该工作。

或者有什么理由不使用googleapiclient


我正在尝试将视频从 S3 存储桶上传到 YouTube

我怀疑您是否可以将其他站点的文件直接上传到Youtube。可能您无法选择从自己的服务器/驱动器上传文件。我在互联网上查找过,但我发现的只是你不能(尽管过去你可以)。人们可以想象为什么不允许这样做的原因有很多(主要是版权,但并非排他性的)。

更新:

可能这不是一个详尽的代码片段。特别是,考虑到您需要OAuth2

但这是另一个:
https ://github.com/youtube/api-samples/blob/master/python/upload_video.py

还有一个:
https ://developers.google.com/youtube/v3/guides/uploading_a_video

使用OAuth2。在那里您还可以找到有关 的信息client_secrets.json

{
 "web": {
   "client_id": "[[INSERT CLIENT ID HERE]]",
   "client_secret": "[[INSERT CLIENT SECRET HERE]]",
   "redirect_uris": [],
   "auth_uri": "https://accounts.google.com/o/oauth2/auth",
   "token_uri": "https://accounts.google.com/o/oauth2/token"
 }
}

您还可以查看一些现实生活中的项目。例如这个:https ://github.com/HA6Bots/Automatic-Youtube-Reddit-Text-To-Speech-Video-Generator-and-Uploader/tree/master/Youtube%20Bot%20Video%20Generator


推荐阅读