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})
相关推荐
小小测试开发2 小时前
安装 Python 3.10+
开发语言·人工智能·python
梦想不只是梦与想2 小时前
Python 中的装饰器
python·装饰器
我叫唧唧波3 小时前
Python+AI 全栈学习笔记
人工智能·python·学习
copyer_xyf3 小时前
Python 异常处理
前端·后端·python
麻雀飞吧4 小时前
期货多合约策略目标持仓怎么更新才不乱
python·区块链
Cthy_hy4 小时前
拓扑排序超详解:原理 + Kahn 贪心算法
python·算法·贪心算法
LSssT.4 小时前
【01】Python 机器学习
开发语言·python
为爱停留5 小时前
给智能体装上「刹车」:中断(Interrupts)与人工审批全解析
python
l1t5 小时前
DeepSeek总结的使用实体-组件-系统和基于存在性处理进行Python编程39-40
开发语言·python
曾阿伦5 小时前
Python 搭建简易HTTP服务
开发语言·python·http