栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

fastapi 模板渲染

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

fastapi 模板渲染

项目下创建 templates 文件夹

安装依赖包

pip install jinja2 aiofiles
# aiofiles是静态网页需要的包
# 特别说明的是 Starlette 是一个轻量级 ASGI 框架/工具包 FastAPI一大特色。

index.py

from fastapi import APIRouter
from starlette.requests import Request
from starlette.staticfiles import StaticFiles
from starlette.templating import Jinja2Templates
router APIRouter()
templates Jinja2Templates(directory templates )
# Request在路径操作中声明一个参数 该参数将返回模板。
# 使用templates您创建的渲染并返回TemplateResponse 并request在Jinja2“上下文” 中将用作键值对之一。
 router.get( /index/{id}/{name} )
async def read_item(request: Request, id: str,name: str):
 return templates.TemplateResponse( index.html , { request : request, id : id, name :name})

index.html ( templates/index.html

 html 
 head 
 title index /title 
 style type text/css 
 /style 
 /head 
 body 
 div 
 p {{name}} /p 
 /div 
 /body 
 /html 
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/267930.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号