from fastapi import FastAPI,Request
from fastapi.templating import Jinja2Templates
from fastapi.responses import HTMLResponse
import uvicorn
app = FastAPI()
templates = Jinja2Templates(directory="templates")
@app.get('/hello/{name}', response_class=HTMLResponse)#这里的参数名不能写错,会报错,如,responses=HTMLResponse,报错TypeError: 'type' object is not a mapping
def hello(request:Request,name:str ):#建议将参数名小写,以符合Python的命名规范。
#return templates.TemplateResponse('hello.html',request=request,name=name)
return templates.TemplateResponse('hello.html',{'request': request,"name":name})
if __name__ == "__main__":
uvicorn.run(
app='fastapiHello:app',
host="127.0.0.1",
port=8000, reload=True
)
hello.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>hello</title>
</head>
<body>
<h1>hello{{name}},goodluck!</h1>
</body>
</html>