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

部署后的FastAPI服务器调用Genius API遭Cloudflare 403拦截(本地运行正常)的解决方案咨询

部署后的FastAPI服务器调用Genius API遭Cloudflare 403拦截(本地运行正常)的解决方案咨询

我最近做了个FastAPI服务,用来对接Genius的歌词API(用的是lyricsgenius库),核心需求是不想把Genius的API密钥暴露给桌面端前端,所以把密钥存在服务器环境变量里,只给前端开放接口调用。

本地跑的时候一切正常,但把服务部署到云服务器上之后,所有请求都被Cloudflare拦了,返回403,还带了一堆验证码相关的HTML。我试过给lyricsgenius加了浏览器的User-Agent,但好像没起作用,想问问大家有没有遇到过类似情况?是Genius故意限制服务器端请求,还是有什么办法能绕开这个拦截?

先贴一下我的服务代码片段:

import os
import json
import sys
from fastapi import FastAPI
from fastapi.responses import StreamingResponse
from pydantic import BaseModel
import lyricsgenius

app = FastAPI()

GENIUS_ACCESS_TOKEN = os.getenv("GENIUS_TOKEN")
if GENIUS_ACCESS_TOKEN:
    # 试过加User-Agent伪装成浏览器,但没用
    genius = lyricsgenius.Genius(
        GENIUS_ACCESS_TOKEN,
        remove_section_headers=True,
        skip_non_songs=False,
        user_agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64)"
    )
else:
    print("Fatal error: genius could not be started")
    sys.exit(1)

# 定义请求模型
class Cancion(BaseModel):
    titulo: str
    artista: str

class Payload(BaseModel):
    items: list[Cancion]

async def buscar_cancion(cancion: Cancion):
    letra = ''
    error = ''
    try:
        # 就是这行代码在部署环境触发403
        song_genius = genius.search_song(cancion.titulo, cancion.artista)
        if song_genius:
            letra = song_genius.lyrics
        else:
            error = "未找到对应歌曲"
    except Exception as e:
        error = str(e)
        print(f"请求失败: {e}")
    return {"titulo": cancion.titulo, "artista": cancion.artista, "letra": letra, "error": error}

async def process_song_list(canciones: list[Cancion]):
    for cancion in canciones:
        resultado = await buscar_cancion(cancion)
        yield json.dumps(resultado) + '\n'

@app.post("/api/procesar")
async def procesar(canciones: Payload):
    return StreamingResponse(process_song_list(canciones.items), media_type="application/json")

我目前的尝试和疑问

  • 加了浏览器的User-Agent,但部署后还是被拦,是不是lyricsgenius库没有正确传递这个User-Agent?
  • Genius的API是不是不允许服务器端的批量/自动化请求?还是Cloudflare的验证逻辑除了User-Agent还有其他检测项?
  • 有没有办法让lyricsgenius或者我的FastAPI服务通过Cloudflare的验证?比如加更多请求头,或者用代理?

希望有经验的大佬给点思路,谢谢!

内容来源于stack exchange

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.07 08:24:31