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})
相关推荐
AC赳赳老秦8 小时前
OpenClaw SEO写手Agent实操:生成结构化文章,适配CSDN搜索规则
大数据·人工智能·python·搜索引擎·去中心化·deepseek·openclaw
廖圣平8 小时前
从零开始,福袋直播间脚本研究【八】《策略模式》
开发语言·python·bash·策略模式
2301_804215418 小时前
Python类型提示(Type Hints)详解
jvm·数据库·python
第一程序员8 小时前
非专业转码心路历程与Rust学习规划
python·github
一帧一画8 小时前
基于 CNN+LSTM 的全国年度降水预测实践
python·cnn·lstm
骄阳似火_20188 小时前
Anaconda的详细安装步骤
python
Thomas.Sir8 小时前
第八章:Python3 之 异常与文件处理【从基础入门到底层原理+项目实战】
python·ai·文件处理·异常
2301_816651228 小时前
用户认证与授权:使用JWT保护你的API
jvm·数据库·python
Sunshine for you8 小时前
Python单元测试(unittest)实战指南
jvm·数据库·python
wefly20178 小时前
m3u8live.cn:免安装 HLS 在线播放器,流媒体调试效率神器
开发语言·javascript·python·django·ecmascript·hls.js 原理·m3u8 解析