4fastapi驱动前端页面

1需要安装模板引擎

2后台程序需要引入Request和Jinja2Templates

3函数至少需要设疑一个参数用于接收request对象

示例:

1在项目目中中新建一个文件夹pages用于存放HTML页面(fastapi_demo/pages/index.html)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1><p>欢迎来到fastapi</p></h1>
<p>小试牛刀</p>
<p>用户名:{{ name }}</p>
</body>
</html>

2编写函数:

from fastapi import FastAPI, Request
import uvicorn
from fastapi.templating import Jinja2Templates
app = FastAPI()
#存放网页的路径
template = Jinja2Templates("pages")

@app.get("/")
def user(username,req:Request):
    return template.TemplateResponse("index.html",context={"request":req,"name":username})

3启动项目并浏览器访问测试:

uvicorn d03_request_params:app --reload
http://127.0.0.1:8000/?username=helloWorld

 

posted @ 2021-12-30 22:02  linuxTang  阅读(390)  评论(0编辑  收藏  举报