· 约 2 分钟

12-FastAPI基础入门-响应类型-文件格式

  • FastAPI
  • Python

学习目标

核心概念

代码示例

from pathlib import Path

from fastapi import FastAPI, HTTPException
from fastapi.responses import FileResponse

app = FastAPI()
BASE_DIR = Path(__file__).resolve().parent


@app.get("/download-guide")
def download_guide():
    file_path = BASE_DIR / "files" / "fastapi_guide.pdf"
    if not file_path.exists():
        raise HTTPException(status_code=404, detail="文件不存在")
    return FileResponse(
        path=file_path,
        filename="fastapi_guide.pdf",
        media_type="application/pdf",
    )

案例理解

易错点

我的补充