FastAPI挂载静态资源

FastAPI挂载静态资源

使用场景:前后端不分离,后端挂载图片,css,js等静态资源,给客户端响应html页面

首先假设项目根目录为app,app目录下的static为存放静态资源的目录

python 复制代码
#app/main.py
from fastapi import FastAPI

app = FastAPI()

#挂载静态资源
app.mount("/static", StaticFiles(directory="app/static"), name="static")

如上即可成功挂载

在app目录的view为html页面资源

复制代码
from fastapi import APIRouter
from fastapi.templating import Jinja2Templates
from fastapi.responses import HTMLResponse

router = APIRouter()
template = Jinja2Templates(r"app/views")

@router.get("/index", response_class=HTMLResponse)
def index(request: Request):
    return template.TemplateResponse("index.html", context={"request": request})
相关推荐
q1234567890989 小时前
FNN sin predict
开发语言·python
先做个垃圾出来………10 小时前
Python字节串“b“前缀
开发语言·python
dreams_dream10 小时前
什么是迭代器和生成器
python
悠闲蜗牛�11 小时前
深入浅出Spring Boot 3.x:新特性全解析与实战指南
开发语言·python
xinhuanjieyi11 小时前
python获取租房70页信息,为了安全隐去了真实网址
开发语言·python
gzroy11 小时前
量化金融实践-海龟交易法
python·金融
sg_knight11 小时前
适配器模式(Adapter)
python·设计模式·适配器模式·adapter
52Hz11812 小时前
力扣20.有效的括号、155.最小栈
python·算法·leetcode
小鸡吃米…12 小时前
TensorFlow 实现多层感知机学习
人工智能·python·tensorflow