質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.50%
Google API

Googleは多種多様なAPIを提供していて、その多くはウェブ開発者向けのAPIです。それらのAPIは消費者に人気なGoogleのサービス(Google Maps, Google Earth, AdSense, Adwords, Google Apps,YouTube等)に基づいています。

OAuth 2.0

OAuth 2.0(Open Authorization 2.0)は、APIを通して保護されたリソース(サードパーティのアプリケーション)へアクセスする為のオープンプロトコルです。

Python 3.x

Python 3はPythonプログラミング言語の最新バージョンであり、2008年12月3日にリリースされました。

YouTube API

YouTube APIはYouTubeのビデオコンテンツと機能性をウェブサイト、アプリケーション、デバイスに統合することを可能にします。

Q&A

解決済

1回答

1543閲覧

python YouTubeAPIを利用した動画のアップロード

yyy054

総合スコア1

Google API

Googleは多種多様なAPIを提供していて、その多くはウェブ開発者向けのAPIです。それらのAPIは消費者に人気なGoogleのサービス(Google Maps, Google Earth, AdSense, Adwords, Google Apps,YouTube等)に基づいています。

OAuth 2.0

OAuth 2.0(Open Authorization 2.0)は、APIを通して保護されたリソース(サードパーティのアプリケーション)へアクセスする為のオープンプロトコルです。

Python 3.x

Python 3はPythonプログラミング言語の最新バージョンであり、2008年12月3日にリリースされました。

YouTube API

YouTube APIはYouTubeのビデオコンテンツと機能性をウェブサイト、アプリケーション、デバイスに統合することを可能にします。

0グッド

0クリップ

投稿2020/05/05 01:50

実現したいこと

YouTubeAPIを利用して動画をアップロードしたと考えています。
初心者ながら、なんとかコードを下記実行したところ、
Googleの画面に移るのですが

"承認エラー"
エラー 401: invalid_client
The OAuth client was not found.

となってしまいます。

発生している問題・エラーメッセージ

/Users/****/.pyenv/versions/3.8.0/lib/python3.8/site-packages/oauth2client/_helpers.py:255: UserWarning: Cannot access upload_video.py-oauth2.json: No such file or directory warnings.warn(_MISSING_FILE_MESSAGE.format(filename)) Your browser has been opened to visit: https://accounts.google.com/o/oauth2/auth?client_id=%5B738329506660-vohrpbrn58dcorfmhtnnifqfeglqka1k.apps.googleusercontent.com%5D&redirect_uri=http%3A%2F%2Flocalhost%3A8080%2F&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fyoutube.upload&access_type=offline&response_type=code If your browser is on a different machine then exit and re-run this application with the command-line parameter --noauth_local_webserver

該当のソースコード

python

1import http.client 2import httplib2 3import os 4import random 5import sys 6import time 7 8from googleapiclient.discovery import build 9from googleapiclient.errors import HttpError 10from googleapiclient.http import MediaFileUpload 11from oauth2client.client import flow_from_clientsecrets 12from oauth2client.file import Storage 13from oauth2client.tools import argparser, run_flow 14 15 16# Explicitly tell the underlying HTTP transport library not to retry, since 17# we are handling retry logic ourselves. 18httplib2.RETRIES = 1 19 20# Maximum number of times to retry before giving up. 21MAX_RETRIES = 10 22 23# Always retry when these exceptions are raised. 24RETRIABLE_EXCEPTIONS = (httplib2.HttpLib2Error, 25 IOError, http.client.NotConnected, 26 http.client.IncompleteRead, 27 http.client.ImproperConnectionState, 28 http.client.CannotSendRequest, 29 http.client.CannotSendHeader, 30 http.client.ResponseNotReady, 31 http.client.BadStatusLine) 32 33# Always retry when an apiclient.errors.HttpError with one of these status 34# codes is raised. 35RETRIABLE_STATUS_CODES = [500, 502, 503, 504] 36 37# The CLIENT_SECRETS_FILE variable specifies the name of a file that contains 38# the OAuth 2.0 information for this application, including its client_id and 39# client_secret. You can acquire an OAuth 2.0 client ID and client secret from 40# the Google API Console at 41# https://console.developers.google.com/. 42# Please ensure that you have enabled the YouTube Data API for your project. 43# For more information about using OAuth2 to access the YouTube Data API, see: 44# https://developers.google.com/youtube/v3/guides/authentication 45# For more information about the client_secrets.json file format, see: 46# https://developers.google.com/api-client-library/python/guide/aaa_client_secrets 47CLIENT_SECRETS_FILE = "client_secrets.json" 48 49# This OAuth 2.0 access scope allows an application to upload files to the 50# authenticated user's YouTube channel, but doesn't allow other types of access. 51YOUTUBE_UPLOAD_SCOPE = "https://www.googleapis.com/auth/youtube.upload" 52YOUTUBE_API_SERVICE_NAME = "youtube" 53YOUTUBE_API_VERSION = "v3" 54 55# This variable defines a message to display if the CLIENT_SECRETS_FILE is 56# missing. 57MISSING_CLIENT_SECRETS_MESSAGE = """ 58WARNING: Please configure OAuth 2.0 59 60To make this sample run you will need to populate the client_secrets.json file 61found at: 62 63 %s 64 65with information from the API Console 66https://console.developers.google.com/ 67 68For more information about the client_secrets.json file format, please visit: 69https://developers.google.com/api-client-library/python/guide/aaa_client_secrets 70""" % os.path.abspath(os.path.join(os.path.dirname(__file__), 71 CLIENT_SECRETS_FILE)) 72 73VALID_PRIVACY_STATUSES = ("public", "private", "unlisted") 74 75 76def get_authenticated_service(args): 77 flow = flow_from_clientsecrets(CLIENT_SECRETS_FILE, 78 scope=YOUTUBE_UPLOAD_SCOPE, 79 message=MISSING_CLIENT_SECRETS_MESSAGE) 80 81 storage = Storage("%s-oauth2.json" % sys.argv[0]) 82 credentials = storage.get() 83 84 if credentials is None or credentials.invalid: 85 credentials = run_flow(flow, storage, args) 86 87 return build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION, 88 http=credentials.authorize(httplib2.Http())) 89 90def initialize_upload(youtube, options): 91 tags = None 92 if options.keywords: 93 tags = options.keywords.split(",") 94 95 body=dict( 96 snippet=dict( 97 title=options.title, 98 description=options.description, 99 tags=tags, 100 categoryId=options.category 101 ), 102 status=dict( 103 privacyStatus=options.privacyStatus 104 ) 105 ) 106 107 # Call the API's videos.insert method to create and upload the video. 108 insert_request = youtube.videos().insert( 109 part=",".join(body.keys()), 110 body=body, 111 # The chunksize parameter specifies the size of each chunk of data, in 112 # bytes, that will be uploaded at a time. Set a higher value for 113 # reliable connections as fewer chunks lead to faster uploads. Set a lower 114 # value for better recovery on less reliable connections. 115 # 116 # Setting "chunksize" equal to -1 in the code below means that the entire 117 # file will be uploaded in a single HTTP request. (If the upload fails, 118 # it will still be retried where it left off.) This is usually a best 119 # practice, but if you're using Python older than 2.6 or if you're 120 # running on App Engine, you should set the chunksize to something like 121 # 1024 * 1024 (1 megabyte). 122 media_body=MediaFileUpload(options.file, chunksize=-1, resumable=True) 123 ) 124 125 resumable_upload(insert_request) 126 127# This method implements an exponential backoff strategy to resume a 128# failed upload. 129def resumable_upload(insert_request): 130 response = None 131 error = None 132 retry = 0 133 while response is None: 134 try: 135 print("Uploading file...") 136 status, response = insert_request.next_chunk() 137 if response is not None: 138 if 'id' in response: 139 print("Video id '%s' was successfully uploaded." % response['id']) 140 else: 141 exit("The upload failed with an unexpected response: %s" % response) 142 except HttpError as e: 143 if e.resp.status in RETRIABLE_STATUS_CODES: 144 error = "A retriable HTTP error %d occurred:\n%s" % (e.resp.status, 145 e.content) 146 else: 147 raise 148 except RETRIABLE_EXCEPTIONS as e: 149 error = "A retriable error occurred: %s" % e 150 151 if error is not None: 152 print(error) 153 retry += 1 154 if retry > MAX_RETRIES: 155 exit("No longer attempting to retry.") 156 157 max_sleep = 2 ** retry 158 sleep_seconds = random.random() * max_sleep 159 print("Sleeping %f seconds and then retrying..." % sleep_seconds) 160 time.sleep(sleep_seconds) 161 162if __name__ == '__main__': 163 argparser.add_argument("--file", required=True, help="Video file to upload") 164 argparser.add_argument("--title", help="Video title", default="Test Title") 165 argparser.add_argument("--description", help="Video description", 166 default="Test Description") 167 argparser.add_argument("--category", default="22", 168 help="Numeric video category. " + 169 "See https://developers.google.com/youtube/v3/docs/videoCategories/list") 170 argparser.add_argument("--keywords", help="Video keywords, comma separated", 171 default="") 172 argparser.add_argument("--privacyStatus", choices=VALID_PRIVACY_STATUSES, 173 default=VALID_PRIVACY_STATUSES[0], help="Video privacy status.") 174 args = argparser.parse_args() 175 176 if not os.path.exists(args.file): 177 exit("Please specify a valid file using the --file= parameter.") 178 179 youtube = get_authenticated_service(args) 180 try: 181 initialize_upload(youtube, args) 182 except HttpError as e: 183 print("An HTTP error %d occurred:\n%s" % (e.resp.status, e.content))

該当のソースコード

JSON

1{ 2 "web": { 3 "client_id": "[*****-vohrpbrn58dcorfmhtnnifqfeglqka1k.apps.googleusercontent.com]", 4 "client_secret": "[*****WmK7jHtG2UmHF]", 5 "redirect_uris": [], 6 "auth_uri": "https://accounts.google.com/o/oauth2/auth", 7 "token_uri": "https://accounts.google.com/o/oauth2/token" 8 } 9}

実行

cmd

1python upload_video.py --file="*****ovies/IMG-1378.MOV" \ 2 --title="Sample Movie" \ 3 --description="This is a sample movie." \ 4 --category="22" \ 5 --privacyStatus="private"

試したこと

ID、secretの再確認(スペース等も含め)
OAuth 2.0 クライアント IDの再発行(アカウント再作成)
その他、調べてみましたが原因がわかりません。

ご教授のほど、お願いいたします。

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答1

0

ベストアンサー

UserWarning: Cannot access upload_video.py-oauth2.json: No such file or directory

authのためのファイル参照が間違っているのではないでしょうか?

# スクリプト実行→ authのためのjsonファイルを参照 → jsonが参照できず401のunauthorizedになる python upload_video.py

もう一度パスとか調べてみてください

投稿2020/05/05 02:42

hiyashikyuri

総合スコア388

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

yyy054

2020/05/05 21:29

回答ありがとうございます。 やはり、ご指摘頂いたあたりのようです。引き続き解決のために作業してみます
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.50%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問