python-2.7 - YouTube视频插入返回 “default”视频资源

标签 python-2.7 youtube youtube-api youtube-data-api

我正在尝试将视频从S3存储桶上传到YouTube,并返回奇怪的输出,这意味着发布成功,但没有提供任何预期的结果。同样,我在代码中设置了titledescription之类的属性,但是从输出中可以看到,实际上并没有设置该属性。

示例输出:

{
  "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

最佳答案

I have also tried downloading the file from S3 and uploading with the file directly, and I get the same result.



您可能有这个问题,可能是由于您实际上并未发送文件。 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

I'm trying to upload a video from an S3 bucket to YouTube



我怀疑您是否可以将文件从其他站点直接上传到Youtube。可能您会选择从自己的服务器/驱动器上载文件。我已经在Internet上查询了,但是发现的却是(虽然过去可以),但您不能这样做。人们可以想象出不允许这样做的很多原因(主要是版权,但不是排他性的)。

更新:

可能这不是一个详尽的代码片段。特别是考虑到您需要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"
 }
}


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

关于python-2.7 - YouTube视频插入返回 “default”视频资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61487934/

相关文章:

python - 了解类型错误: got multiple values for keyword argument

python-2.7 - 使用opencv和python进行人脸检测只能检测眼睛区域

flutter - 如何从 Flutter 应用程序在 google chromecast 中播放 YouTube 视频?

java - 如何使用java按计数从youtube播放列表中获取视频?

python - 需要加入一个列表的元素,但加入后保留元素周围的 ''

Python 包 wheel PKG-INFO 名称

java - 如何使用Java读取文件

youtube - 如何获取实时 m3u8 文件而不是 YouTube 直播流的 DVR m3u8 文件?

swift - 使用 YouTube API (Swift) 对 YouTube 视频进行评分

javascript - 使用 Javascript 的 Chromeless 播放器中的全屏选项?