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})
相关推荐
kcuwu.21 分钟前
Python进阶:生成器与协程,高效并发编程的核心实践
windows·python·php
XiaoQiao66699922 分钟前
python 简单题目练手【详解版】【1】
开发语言·python
ZC跨境爬虫26 分钟前
极验滑动验证码自动化实战:背景提取、缺口定位与Playwright滑动模拟
前端·爬虫·python·自动化
智算菩萨28 分钟前
【Python图像处理】2 数字图像基础与Python图像表示
开发语言·图像处理·python
xiaoshuaishuai81 小时前
Git二分法定位Bug
开发语言·python
2401_835792542 小时前
FastAPI 速通
windows·python·fastapi
YMWM_2 小时前
export MPLBACKEND=Agg命令使用
linux·python
派大星~课堂2 小时前
【力扣-148. 排序链表】Python笔记
python·leetcode·链表
微涼5302 小时前
【Python】在使用联网工具时需要的问题
服务器·python·php
小白菜又菜2 小时前
Leetcode 657. Robot Return to Origin
python·leetcode·职场和发展