FastApi如何返回index页面

FastAPI 中,如果你想返回一个 index.html 页面,可以通过以下几种方式实现。以下是详细讲解和示例代码:


方法 1:使用 FileResponse 返回静态 HTML 文件

FileResponseFastAPI 提供的一个响应类,用于返回文件内容。适合返回静态 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 内容

HTMLResponseFastAPI 提供的一个响应类,用于直接返回 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 内容,使用 HTMLResponseJinja2 模板引擎。
• 如果有多个静态文件,使用 StaticFiles 提供静态文件服务。

根据你的需求选择合适的方法即可!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

鸭梨山大哎

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值