在 FastAPI
中,如果你想返回一个 index.html
页面,可以通过以下几种方式实现。以下是详细讲解和示例代码:
方法 1:使用 FileResponse
返回静态 HTML 文件
FileResponse
是 FastAPI
提供的一个响应类,用于返回文件内容。适合返回静态 HTML 文件。
示例代码
from fastapi import FastAPI
from fastapi.responses import FileResponse
app = FastAPI()
@app.get("/")
async def read_root():
return FileResponse("templates/index.html")
说明
• FileResponse("templates/index.html")
:返回 templates/index.html
文件的内容。
• 需要确保 templates/index.html
文件存在,否则会抛出 FileNotFoundError
异常。
项目结构
my_project/
│
├── main.py
└── templates/
└── index.html
方法 2:使用 HTMLResponse
返回动态 HTML 内容
HTMLResponse
是 FastAPI
提供的一个响应类,用于直接返回 HTML 字符串。适合动态生成 HTML 内容。
示例代码
from fastapi import FastAPI
from fastapi.responses import HTMLResponse
app = FastAPI()
@app.get("/", response_class=HTMLResponse)
async def read_root():
return """
<html>
<head><title>Index Page</title></head>
<body>
<h1>Welcome to FastAPI!</h1>
</body>
</html>
"""
说明
• response_class=HTMLResponse
:指定响应类型为 HTMLResponse
。
• 直接在函数中返回 HTML 字符串。
方法 3:使用 Jinja2
模板引擎渲染 HTML
Jinja2
是一个流行的模板引擎,可以动态生成 HTML 内容。适合需要动态数据的场景。
安装依赖
pip install jinja2
示例代码
from fastapi import FastAPI, Request
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates
app = FastAPI()
templates = Jinja2Templates(directory="templates")
@app.get("/", response_class=HTMLResponse)
async def read_root(request: Request):
return templates.TemplateResponse("index.html", {"request": request, "message": "Welcome to FastAPI!"})
说明
• Jinja2Templates(directory="templates")
:指定模板文件所在的目录(这里是 templates
)。
• templates.TemplateResponse("index.html", {"request": request, "message": "Welcome to FastAPI!"})
:渲染 index.html
模板,并传递动态数据。
项目结构
my_project/
│
├── main.py
└── templates/
└── index.html
templates/index.html
示例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Index Page</title>
</head>
<body>
<h1>{{ message }}</h1>
</body>
</html>
方法 4:使用静态文件服务
如果你有多个静态文件(如 HTML、CSS、JS),可以使用 StaticFiles
来提供静态文件服务。
示例代码
from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles
app = FastAPI()
# 挂载静态文件目录
app.mount("/static", StaticFiles(directory="static"), name="static")
@app.get("/")
async def read_root():
return FileResponse("static/index.html")
说明
• app.mount("/static", StaticFiles(directory="static"), name="static")
:将 static
目录挂载到 /static
路径。
• 访问 http://localhost:8000/static/index.html
可以直接获取 static/index.html
文件。
项目结构
my_project/
│
├── main.py
└── static/
├── index.html
├── style.css
└── script.js
总结
• 如果只需要返回一个静态 HTML 文件,使用 FileResponse
最简单。
• 如果需要动态生成 HTML 内容,使用 HTMLResponse
或 Jinja2
模板引擎。
• 如果有多个静态文件,使用 StaticFiles
提供静态文件服务。
根据你的需求选择合适的方法即可!