返回

从FastAPI框架中了解模板引擎和Jinja

前端

FastAPI 是一个现代、快速的 Web 框架,用于使用 Python 构建 API。它具有高性能、易于使用和灵活的特性。FastAPI 还支持使用 Jinja 作为模板引擎来渲染 HTML。

Jinja 是一个流行的 Python 模板引擎,用于生成 HTML、XML 和其他格式的文本。它具有强大的功能和易于使用的语法,使其成为构建 Web 应用程序的理想选择。

使用 FastAPI 和 Jinja 创建 Web 应用程序

要使用 FastAPI 和 Jinja 创建 Web 应用程序,您可以按照以下步骤操作:

  1. 安装 FastAPI 和 Jinja
pip install fastapi jinja2
  1. 创建一个 FastAPI 项目
fastapi new_project my_project
  1. 在项目目录中创建一个 templates 目录
mkdir my_project/templates
  1. 在 templates 目录中创建一个 index.html 文件
<!DOCTYPE html>
<html>
<head>
  
</head>
<body>
  <h1>Hello, world!</h1>
</body>
</html>
  1. 在 main.py 文件中导入 FastAPI、Jinja 和 os 模块
from fastapi import FastAPI, Request
from fastapi.templating import Jinja2Templates
import os
  1. 创建一个 FastAPI 实例
app = FastAPI()
  1. 配置 Jinja2Templates
templates = Jinja2Templates(directory="templates")
app.mount("/static", os.path.join(os.getcwd(), "static"), name="static")
  1. 创建一个路由来渲染 index.html 文件
@app.get("/")
async def index(request: Request):
  return templates.TemplateResponse("index.html", {"request": request})
  1. 运行应用程序
uvicorn main:app --reload

现在,您可以访问 http://127.0.0.1 来查看您的 Web 应用程序。

总结

通过本文,您已经了解了如何使用 FastAPI 和 Jinja 来创建 Web 应用程序。FastAPI 提供了快速、灵活的开发环境,而 Jinja 则提供了强大的模板引擎功能。通过这两个工具的结合,您可以轻松创建具有 HTML 渲染功能的 Web 应用程序。