YouTube 核心错误域:服务不可用

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

我有一个 Python 脚本,它使用 YouTube API 将视频添加到我创建的播放列表中。有时该功能有效,但有时,当我尝试执行请求时,我收到此错误消息:

googleapiclient.errors.HttpError: <HttpError 409 when requesting https://youtube.googleapis.com/youtube/v3/playlistItems?part=snippet&alt=json returned "The operation was aborted.". Details: "[{'domain': 'youtube.CoreErrorDomain', 'reason': 'SERVICE_UNAVAILABLE'}]">
为什么它只能在某些时候起作用,最重要的是,这是我的错还是 YouTube 的错?如果是我的错,我该如何解决?这是我调用的函数:

def addSongToPlaylist(self, video_id, playlist_id): # Adds a song to the playlist given
    request = add_video_request=self.youtube_service.playlistItems().insert(
    part="snippet",
    body={
            'snippet': {
                 playlistId': playlist_id, 
                 'resourceId': {
                    'kind': 'youtube#video',
                    'videoId': video_id
                }
            }
        }
    )
    print(video_id)
    response = request.execute()
    return response

我还打印了 video_id 以确保它是一个有效的 id,而且它始终是。感谢任何可以提供帮助的人:)

python flask youtube youtube-api youtube-data-api
1个回答
0
投票

问题出在 youtube sid 上,它可能暂时不可用,一种解决方案是放置一个

retry
机制,以便它可以处理那些服务干扰。 以下是您如何在代码中执行此操作:

import time
from googleapiclient.errors import HttpError

def addSongToPlaylist(self, video_id, playlist_id): # Adds a song to the playlist given
    max_retries = 5
    retry_count = 0
    backoff_time = 1  # In seconds

    while retry_count < max_retries:
        try:
            request = self.youtube_service.playlistItems().insert(
                part="snippet",
                body={
                    'snippet': {
                        'playlistId': playlist_id,
                        'resourceId': {
                            'kind': 'youtube#video',
                            'videoId': video_id
                        }
                    }
                }
            )
            print(video_id)
            response = request.execute()
            return response
        except HttpError as e:
            if e.resp.status == 409 and 'SERVICE_UNAVAILABLE' in str(e):
                retry_count += 1
                print(f"Attempt {retry_count} failed. Retrying in {backoff_time} seconds...")
                time.sleep(backoff_time)
                backoff_time *= 2  # Exponential backoff
            else:
                raise
    raise Exception("Failed to add the song to the playlist after multiple retries.")
© www.soinside.com 2019 - 2024. All rights reserved.