FastAPI - 模板


默认情况下,FastAPI 向客户端呈现 JSON 响应。但是,它可以转换为 HTML 响应。为此,FastAPI在fastapi.responses模块中定义了HTMLResponse类。我们需要将response_class作为附加参数添加到操作装饰器中,并以HTMLResponse对象作为其值。

在以下示例中,@app.get() 装饰器具有“/hello/”端点和作为response_class 的HTMLResponse。在 hello() 函数内,我们有一个 Hello World 消息的 HTML 代码的字符串表示形式。该字符串以 HTML 响应的形式返回。

from fastapi.responses import HTMLResponse
from fastapi import FastAPI
app = FastAPI()
@app.get("/hello/")
async def hello():
   ret='''
<html>
<body>
<h2>Hello World!</h2>
</body>
</html>
'''
   return HTMLResponse(content=ret)

通过检查 API 文档,可以看出服务器的响应正文是 HTML 格式的。

FastAPI 模板

请求 URL (http://localhost:8000/hello/) 也应该在浏览器中呈现消息。然而,呈现原始 HTML 响应非常乏味。或者,可以将预构建的 HTML 页面呈现为模板。为此,我们需要使用网页模板库。

Web 模板库有一个模板引擎,可以合并具有占位符变量的静态网页。来自任何来源(例如数据库)的数据被合并以动态生成和呈现网页。FastAPI没有任何预先打包的模板库。因此,人们可以自由地使用任何适合他需要的一种。在本教程中,我们将使用jinja2,一个非常流行的 Web 模板库。让我们首先使用 pip 安装程序安装它。

pip3 install jinja2

FastAPI 对 Jinja 模板的支持以 fastapi.templates 模块中定义的jinja2Templates类的形式提供。

from fastapi.templating import Jinja2Templates

要声明模板对象,应将存储 html 模板的文件夹作为参数提供。在当前工作目录中,我们将创建一个“templates”目录。

templates = Jinja2Templates(directory="templates")

用于呈现 Hello World 消息的简单网页“hello.html”也放置在“templates”文件夹中。

<html>
<body>
<h2>Hello World!</h2>
</body>
</html>

我们现在要将此页面的 html 代码呈现为 HTMLResponse。让我们修改 hello() 函数如下 -

from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates
from fastapi import FastAPI, Request
app = FastAPI()
templates = Jinja2Templates(directory="templates")
@app.get("/hello/", response_class=HTMLResponse)
async def hello(request: Request):
   return templates.TemplateResponse("hello.html", {"request": request})

这里,模板对象的templateResponse()方法收集模板代码和请求上下文来呈现 http 响应。当我们启动服务器并访问 http://localhost:8000/hello/ URL 时,我们会在浏览器中看到Hello World消息,这实际上是hello.html的输出

FastAPI 模板

如前所述,jinja2 模板允许将某些占位符嵌入 HTML 代码中。jinja2 代码元素放在大括号内。一旦浏览器的 HTML 解析器遇到这种情况,模板引擎就会接管并通过 HTTP 响应提供的变量数据填充这些代码元素。Jinja2 提供以下代码元素 -

  • {% %} – 语句

  • {{ }} – 要打印到模板输出的表达式

  • {# #} - 不包含在模板输出中的注释

  • # # # - 行语句

hello.html修改如下,通过替换 name 参数来显示动态消息

<html>
<body>
<h2>Hello {{name}} Welcome to FastAPI</h2>
</body>
</html>

操作函数hello()也被修改为接受名称作为路径参数。TemplateResponse还应包含“name”的 JSON 表示形式name以及请求上下文。

from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates
from fastapi import FastAPI, Request
app = FastAPI()
templates = Jinja2Templates(directory="templates")
@app.get("/hello/{name}", response_class=HTMLResponse)
async def hello(request: Request, name:str):
   return templates.TemplateResponse("hello.html", {"request": request, "name":name})

重新启动服务器并访问 http://localhost:8000/hello/Kiran。浏览器现在使用此 URL 中的路径参数填充 jinja2 占位符。

FastAPI 模板