如何在FastAPI的RedirectResponse中携带音频文件请求体?
解决FastAPI中RedirectResponse无法传递文件到POST端点的问题
你当前的写法存在两个核心问题:
RedirectResponse本质是触发客户端发起新的HTTP请求,而URL参数仅支持传递字符串,无法直接传递UploadFile这类文件对象;- 重定向请求默认使用GET方法,即便强制用307/308状态码保留POST方法,也无法自动将原请求的文件数据携带到新请求中。
下面提供两种可行的解决思路:
思路一:内部函数调用(推荐,无额外开销)
既然两个端点同属一个FastAPI应用,没必要走HTTP重定向,直接在/check里调用check_base的处理逻辑,把文件参数直接传入:
from io import BytesIO from fastapi import UploadFile, File @router.post("/check") async def check(request: Request): # 读取本地音频文件并构造符合UploadFile要求的对象 with open("/home/hello.wav", "rb") as f: file_content = f.read() audio_file = UploadFile( filename="hello.wav", file=BytesIO(file_content) ) # 直接调用check_base函数处理文件 result = await check_base(request, audio=audio_file) return result @router.post("/check_base") async def check_base( request: Request, audio: UploadFile = File(...) ): # 这里编写音频文件处理逻辑 content = await audio.read() return {"filename": audio.filename, "file_size": len(content)}
思路二:临时文件中转(适用于必须重定向的场景)
如果业务上必须使用重定向,可先将文件保存到临时目录,把临时文件路径作为URL参数传递给/check_base,处理完成后再删除临时文件:
import tempfile import os @router.post("/check") async def check(request: Request): # 创建临时文件并复制原音频内容 with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as tmp: with open("/home/hello.wav", "rb") as f: tmp.write(f.read()) tmp_path = tmp.name # 生成带临时路径参数的重定向URL redirect_url = app.url_path_for("check_base", tmp_file_path=tmp_path) return RedirectResponse(url=redirect_url) @router.post("/check_base") async def check_base( request: Request, tmp_file_path: str ): # 读取临时文件内容 with open(tmp_file_path, "rb") as f: content = f.read() # 编写音频处理逻辑 result = {"filename": os.path.basename(tmp_file_path), "file_size": len(content)} # 清理临时文件 os.unlink(tmp_file_path) return result
注意:这种方式需要确保临时文件目录有读写权限,建议增加异常处理来避免临时文件残留。
内容的提问来源于stack exchange,提问作者dinesh palganesan
相关产品推荐
相关产品推荐

