Youtube Data Api v3 的 Oauth 2.0 运行流程不起作用 - 缓存问题?

问题描述 投票:0回答:1

我想通过命令行(提示)使用以下Python代码和google api“Youtube Data Api v3”将视频上传到youtube。

首次执行代码时,Oauth 2.0 运行流程启动。 提示中会出现一个屏幕,询问用户的许可以自动将视频上传到频道。

授予权限,将创建一个带有令牌的文件,这将避免下次运行时出现确认屏幕。 我使用 google 云帐户和 youtube 频道执行了这些步骤,并且成功了。

但现在它不再起作用了。

import os
import json
import sys
import time
import http.client  
import httplib2
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, http.client.NotConnected,
  http.client.IncompleteRead, http.client.ImproperConnectionState,
  http.client.CannotSendRequest, http.client.CannotSendHeader,
  http.client.ResponseNotReady, http.client.BadStatusLine)  

# Always retry when an apiclient.errors.HttpError with one of these status
# codes is raised.
RETRIABLE_STATUS_CODES = [500, 502, 503, 504]

CLIENT_SECRETS_FILE ="api-google/client_secret_xxx.apps.googleusercontent.com.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 API Console
https://console.cloud.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,
            chennelId= "xxx"  # id youtube channel             
        ),
        status=dict(
            privacyStatus=options.privacyStatus,
            madeForKids=False,
            selfDeclaredMadeForKids=False
        )
    )

    # Call the API's videos.insert method to create and upload the video.
    insert_request = youtube.videos().insert(
    part=",".join(body.keys()),
    body=body,
    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 response is not None:
                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 as 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)


#upload video
def carico_short(path_video, folder_video):
     
    percorso_cartella = os.path.join(path_video, folder_video) 
    video_youtube = os.path.join(percorso_cartella, "video_youtube.mp4")  
    
    class ArgsNamespace:
        file = video_youtube
        title = "title"
        description = "content"
        category = "24" #24 è intrattenimento, prima era 22
        keywords = "shorts, curiosity"
        privacyStatus = "public"

    args = ArgsNamespace()     

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


# code to upload the video
cartella_output = "C:\\Users\\user\\Desktop\\canale youtube\\video-4-dopo-non-pubblicati"
carico_short(cartella_output, "folder")

现在我有NEW云控制台帐户和newyoutube频道。 但电脑是一样的。

如果我执行代码,运行流程不起作用:授权请求不会出现在提示中(应该是第一次出现)

我有这个错误:

C:\Users\Giovanni\AppData\Local\Programs\Python\Python310\lib\site-packages\oauth2client\_helpers.py:255: UserWarning: Cannot access myscript.py-oauth2.json: No such file or directory
  warnings.warn(_MISSING_FILE_MESSAGE.format(filename))

编辑

C:\Users\Giovanni\AppData\Local\Programs\Python\Python310\lib\site-packages\oauth2client\_helpers.py:255:    UserWarning: Cannot access myscript.py-oauth2.json:     No such file or directory
 warnings.warn(_MISSING_FILE_MESSAGE.format(filename))
Traceback (most recent call last):
  File "C:\Users\Giovanni\Desktop\canale youtube\myscript.py", line 258, in carico_short
   youtube = get_authenticated_service(args)
  File "C:\Users\Giovanni\Desktop\canale youtube\myscript.py", line 99, in get_authenticated_service
   credentials = run_flow(flow, storage, args)
  File "C:\Users\Giovanni\AppData\Local\Programs\Python\Python310\lib\site-packages\oauth2client\_helpers.py", line 133, in positional_wrapper
    return wrapped(*args, **kwargs)
  File "C:\Users\Giovanni\AppData\Local\Programs\Python\Python310\lib\site-packages\oauth2client\tools.py", line 195, in run_flow
    logging.getLogger().setLevel(getattr(logging, flags.logging_level))
AttributeError: 'ArgsNamespace' object has no attribute 'logging_level'

我怀疑 google/youtube 有一些缓存。

也许对于 YouTube,计算机显示旧帐户的授权? 是这样吗?我怎样才能删除它?

非常感谢

python google-cloud-platform oauth-2.0 youtube youtube-data-api
1个回答
1
投票

根据错误消息和

run_flow
代码,似乎如果未找到
logging_level
arg,则它是从 CLI 获取的。

尝试像这样更新

ArgsNamespace
类:

class ArgsNamespace:
    file = video_youtube
    title = "title"
    description = "content"
    category = "24" #24 è intrattenimento, prima era 22
    keywords = "shorts, curiosity"
    privacyStatus = "public"
    logging_level = "INFO"

更好

更好的是,按照预期使用流程...

  • 使用
    ArgsNamespace
    类来存储您要覆盖的 CLI 标志(在本例中仅为
    logging_level
    ),并使用
    UploadOptions
    来存储您将在函数中使用的上传选项
  • 将两个类定义为
    dataclass
    es(无需实例化对象)
from dataclasses import dataclass

# [...]

@dataclass
class ArgsNamespace:
    logging_level = "INFO"

@dataclass
class UploadOptions:
    file = video_youtube
    title = "title"
    description = "content"
    category = "24" #24 è intrattenimento, prima era 22
    keywords = "shorts, curiosity"
    privacyStatus = "public"

try:                        
    youtube = get_authenticated_service(ArgsNamespace)
    initialize_upload(youtube, UploadOptions)                            
except HttpError as e:  # Definisci e come un'eccezione HttpError
    print("An HTTP error %d occurred:\n%s" % (e.resp.status, e.content))
© www.soinside.com 2019 - 2024. All rights reserved.