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})
相关推荐
OPEN-F7 分钟前
ROS2系列教程:tf2坐标变换详解(C++/Python)
开发语言·c++·python
2601_9620973612 分钟前
Python工作流实战:SpiffWorkflow深度应用与BPMN自动化指南
python·自动化·工作流·bpmn·spiffworkflow
baopixiaoz34 分钟前
BeeQuant × BeeAgent:AI驱动智能交易
大数据·人工智能·python·区块链
公爵爱学习44 分钟前
无人机定点飞行-介绍
开发语言·图像处理·python·学习·线性回归·无人机
stillstream_ink44 分钟前
OpenCart UI 自动化测试实战:POM 四层架构 + 失败自动截图 + 飞书通知
python·测试
databook1 小时前
Beta 分布:如何用“成功”和“失败”来预测下次尝试
python·数据挖掘·数据分析
zhanghaha13141 小时前
Python进阶教程:27_subprocess 模块 零基础超详细教程
开发语言·python
兄弟加油,别颓废了。1 小时前
bugku题目
开发语言·前端·python
新网企兴1 小时前
2026西安GEO推广选哪家?新网企兴帮您精准获客
人工智能·python
2601_962297481 小时前
一、Python GUI 的十字路口:免费凑活还是付费破局
python·gui·tkinter·customtkinter·bravurasdk