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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值