YouTube Video Insert возвращает видео по умолчанию - PullRequest
1 голос
/ 28 апреля 2020

Я пытаюсь загрузить видео из корзины 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 и загрузить с файлом напрямую, и я получил тот же результат. Без правильных сообщений об ошибках или чего-то, что могло бы отключить go, я действительно не уверен, что делать дальше. Любая помощь очень ценится.

Я также пытался использовать 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

1 Ответ

1 голос
/ 02 мая 2020

Я также пытался загрузить файл с 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 . Вероятно, вы застряли с возможностью загрузки файлов с вашего собственного сервера / диска. Я посмотрел на Inte rnet, но все, что я нашел, это то, что вы не можете (хотя вы могли в прошлом). И можно вообразить множество причин, по которым это недопустимо (в основном авторское право, но не исключительно).

Обновление:

Возможно, это не был исчерпывающий фрагмент кода. Особенно, учитывая, что вам нужно 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

...