FastAPI教程-响应类型-返回HTML 作者:马育民 • 2026-08-15 09:06 • 阅读:10002 # 介绍 FastAPI 有**4种主流返回HTML方式**: - 返回HTML字符串 - **返回HTML文件** - **模板渲染(Jinja2)** - 自定义Response **注意:**FastAPI 默认返回 JSON,想要返回网页HTML,必须使用对应响应类。 # 1. 返回 HTML 字符串 在装饰器中指定 `HTMLResponse`,直接把 html文本作为内容返回。 **应用场景:** 简单页面 ```python from fastapi import FastAPI from fastapi.responses import HTMLResponse app = FastAPI() @app.get("/", response_class=HTMLResponse) async def index(): html_content = """ FastAPI HTML Hello FastAPI HTML 直接返回html字符串 """ return html_content ``` # 2. 返回 HTMLResponse 对象 直接返回 `HTMLResponse(content=html_content)` 对象 与上面直接返回 html字符串 等价 ```python @app.get("/demo") async def demo(): return HTMLResponse("demo页面") ``` 响应头自动设置 `Content-Type: text/html; charset=utf-8` # 3. HTMLResponse对象原理 `HTMLResponse` 继承自 `Response` - `content`:html文本 - `status_code`:状态码,默认200 - `headers`:自定义http头 - `media_type="text/html"` 手动构造完整响应示例: ```python from fastapi.responses import HTMLResponse @app.get("/resp") async def resp(): return HTMLResponse( content="自定义响应", status_code=200, headers={"X‑Custom‑Header":"hello"} ) ``` # 4. 返回HTML文件 使用 `FileResponse` 返回磁盘上的 `.html` 文件。 **应用场景:** 复杂页面 ### 创建 HTML 文件 在 `main.py` 的同级目录,创建 `index.html`,内容如下: ``` Title 学习fastapi ``` ### 修改 main.py 文件 ```python # 增加导入 from fastapi.responses import FileResponse @app.get("/page") async def get_html_file(): # 返回当前目录下 index.html return FileResponse("index.html") ``` ### 特点 直接读取磁盘文件,适合纯静态网页;会自动设置html的content‑type。 ### 注意路径问题 相对路径以程序启动目录为基准,不是py文件所在目录。 **推荐:**用绝对路径,避免路径bug。 # 浏览器访问与接口文档 - 浏览器访问路由:渲染网页 - `/docs`接口文档:会把html源码直接展示在响应体,不会渲染页面,这是正常现象。 原文出处:/show_1GW3riDStUmv.html