You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Replit部署Flask+YouTube API项目报UnknownApiNameOrVersion错误求助

问题描述

我有一个基于Python/HTML的项目,通过YouTube API实现视频推荐功能,本地运行完全正常,但部署到Replit平台后,点击「recommend」按钮时触发错误:googleapiclient.errors.UnknownApiNameOrVersion: name: youtube version: v3。

已尝试过更换API密钥、调整API版本、确认API依赖包已安装,但问题仍未解决。

核心Python代码

from flask import Flask, jsonify, request, render_template
from googleapiclient.discovery import build

app = Flask(__name__)


@app.route('/')
def index():
  return render_template('index.html')


@app.route('/recommend', methods=['GET'])
def recommend():
  # 获取查询参数中的YouTube链接
  youtube_link = request.args.get('link')

  # 从链接中解析视频ID
  video_id = youtube_link.split('v=')[-1]

  # 初始化YouTube API客户端
  youtube = build('youtube',
                  'v3',
                  developerKey='AIzaSy...')

  # 获取视频详情
  video_response = youtube.videos().list(part='snippet', id=video_id).execute()

  # 提取视频标题和频道ID
  video_title = video_response['items'][0]['snippet']['title']
  channel_id = video_response['items'][0]['snippet']['channelId']

  # 获取频道详情
  channel_response = youtube.channels().list(part='snippet,statistics',
                                             id=channel_id).execute()

  # 提取频道标题和订阅数
  channel_title = channel_response['items'][0]['snippet']['title']
  subscriber_count = channel_response['items'][0]['statistics'][
    'subscriberCount']

  # 获取相关视频
  related_response = youtube.search().list(
    part='id,snippet', type='video', relatedToVideoId=video_id).execute()

  # 筛选出订阅数小于1000的频道的相关视频
  recommendations = []
  for item in related_response['items']:
    channel_id = item['snippet']['channelId']
    video_id = item['id']['videoId']

    channel_response = youtube.channels().list(part='statistics',
                                               id=channel_id).execute()

    subscriber_count = int(
      channel_response['items'][0]['statistics']['subscriberCount'])
    if subscriber_count < 1000:
      recommendations.append({
        'id': video_id,
        'title': item['snippet']['title']
      })

  return jsonify(recommendations)


if __name__ == '__main__':
  app.run(host='0.0.0.0', port=5000, debug=True)

完整错误栈

File "/home/runner/SmallChannelReccomender/venv/lib/python3.10/site-packages/flask/app.py", line 2548, in __call__
    return self.wsgi_app(environ, start_response)
  File "/home/runner/SmallChannelReccomender/venv/lib/python3.10/site-packages/flask/app.py", line 2528, in wsgi_app
    response = self.handle_exception(e)
  File "/home/runner/SmallChannelReccomender/venv/lib/python3.10/site-packages/flask/app.py", line 2525, in wsgi_app
    response = self.full_dispatch_request()
  File "/home/runner/SmallChannelReccomender/venv/lib/python3.10/site-packages/flask/app.py", line 1822, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/home/runner/SmallChannelReccomender/venv/lib/python3.10/site-packages/flask/app.py", line 1820, in full_dispatch_request
    rv = self.dispatch_request()
  File "/home/runner/SmallChannelReccomender/venv/lib/python3.10/site-packages/flask/app.py", line 1796, in dispatch_request
    return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args)
  File "/home/runner/SmallChannelReccomender/main.py", line 21, in recommend
    youtube = build('youtube',
  File "/home/runner/SmallChannelReccomender/venv/lib/python3.10/site-packages/googleapiclient/_helpers.py", line 130, in positional_wrapper
    return wrapped(*args, **kwargs)
  File "/home/runner/SmallChannelReccomender/venv/lib/python3.10/site-packages/googleapiclient/discovery.py", line 287, in build
    content = _retrieve_discovery_doc(
  File "/home/runner/SmallChannelReccomender/venv/lib/python3.10/site-packages/googleapiclient/discovery.py", line 404, in _retrieve_discovery_doc
    raise UnknownApiNameOrVersion(
googleapiclient.errors.UnknownApiNameOrVersion: name: youtube  version: v3

可能的解决方案

1. 手动指定API发现文档URL

Replit的网络环境可能无法自动获取Google的API发现文档,尝试直接指定文档地址绕过自动获取:

youtube = build(
    'youtube',
    'v3',
    developerKey='AIzaSy...',
    discoveryServiceUrl='https://www.googleapis.com/discovery/v1/apis/youtube/v3/rest'
)

2. 统一依赖包版本

本地与Replit的google-api-python-client版本可能存在兼容性问题,强制安装稳定版本:
在项目的requirements.txt中添加:

google-api-python-client==2.86.0
flask==2.3.3

然后在Replit控制台执行pip install -r requirements.txt重新安装依赖。

3. 检查API密钥权限与访问限制

前往Google Cloud控制台确认:

  • YouTube Data API v3已启用
  • API密钥的IP限制设置为「无限制」(若之前仅允许本地IP访问)
  • API调用配额未耗尽

4. 离线加载发现文档

提前下载YouTube API的发现文档并打包到项目中,避免网络请求获取文档:

  1. 本地下载文档:访问https://www.googleapis.com/discovery/v1/apis/youtube/v3/rest,保存为youtube_discovery.json并上传到Replit项目
  2. 修改代码初始化客户端:
from googleapiclient.discovery import build_from_document
import json

with open('youtube_discovery.json') as f:
    discovery_doc = json.load(f)

youtube = build_from_document(discovery_doc, developerKey='AIzaSy...')

内容的提问来源于stack exchange,提问作者Stanners

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 15:57:04