推荐答案
在 FastAPI 中返回 HTML 响应可以通过以下步骤实现:
- 使用
Response类,并设置content_type为text/html。 - 将 HTML 内容作为字符串传递给
Response对象。
示例代码如下:
// www.javascriptcn.com code example
from fastapi import FastAPI, Response
app = FastAPI()
@app.get("/html")
def get_html():
html_content = """
<html>
<head><title>FastAPI HTML Response</title></head>
<body>
<h1>Hello, FastAPI!</h1>
</body>
</html>
"""
return Response(content=html_content, media_type="text/html")本题详细解读
1. 使用 Response 类
在 FastAPI 中,Response 类允许你自定义响应的内容和类型。通过设置 content 参数为 HTML 字符串,并将 media_type 参数设置为 "text/html",你可以返回一个 HTML 响应。
2. HTML 内容
HTML 内容可以直接作为字符串传递给 Response 对象。你可以根据需要动态生成 HTML 内容,或者直接使用静态的 HTML 字符串。
3. 路由处理函数
在路由处理函数中,返回 Response 对象即可。FastAPI 会自动处理响应并将其发送给客户端。
4. 其他方式
除了直接使用 Response 类,你还可以使用 HTMLResponse 类来简化代码:
// www.javascriptcn.com code example
from fastapi import FastAPI
from fastapi.responses import HTMLResponse
app = FastAPI()
@app.get("/html", response_class=HTMLResponse)
def get_html():
return """
<html>
<head><title>FastAPI HTML Response</title></head>
<body>
<h1>Hello, FastAPI!</h1>
</body>
</html>
"""这种方式更加简洁,适合返回静态 HTML 内容的场景。