fastapi.templating与HTMLResponse

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

我们现在要把这个页面的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})

一个简单的网页 “hello.html “来呈现 “Hello World “信息,也被放在 “templates “文件夹中

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

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

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

{% %} – 语句
{ { }} – 打印到模板输出的表达式

{# #} – 不包括在模板输出中的注释

# – 行语句

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

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

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

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的位置符
在这里插入图片描述

相关推荐

  1. ==equals

    2023-12-07 05:06:01       51 阅读
  2. ArrayList LinkedList 的选择应用

    2023-12-07 05:06:01       67 阅读
  3. DecontamSCRUB:安装使用

    2023-12-07 05:06:01       67 阅读
  4. PyTorchTensorFlow的安装介绍

    2023-12-07 05:06:01       49 阅读
  5. vectorlist的区别应用?

    2023-12-07 05:06:01       46 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2023-12-07 05:06:01       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2023-12-07 05:06:01       100 阅读
  3. 在Django里面运行非项目文件

    2023-12-07 05:06:01       82 阅读
  4. Python语言-面向对象

    2023-12-07 05:06:01       91 阅读

热门阅读

  1. PyQt学习随笔:QListWidget的addItem方法 Python

    2023-12-07 05:06:01       58 阅读
  2. python进行文件批量命名

    2023-12-07 05:06:01       57 阅读
  3. 如何快速移植(从STM32F103到STM32F407)

    2023-12-07 05:06:01       57 阅读
  4. 用两个栈实现队列(c++实现)

    2023-12-07 05:06:01       55 阅读
  5. praseInt 和 逻辑或连用

    2023-12-07 05:06:01       47 阅读
  6. SpringMVC常用注解

    2023-12-07 05:06:01       45 阅读
  7. Spring Boot学习(三十三):集成kafka

    2023-12-07 05:06:01       69 阅读
  8. RK3288升级WebView版本,替换webview app

    2023-12-07 05:06:01       54 阅读
  9. android 13.0 Camera2去掉前置摄像头闪光灯功能

    2023-12-07 05:06:01       64 阅读