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})
相关推荐
ValhallaCoder26 分钟前
hot100-栈
数据结构·python·算法·
MediaTea4 小时前
Python:生成器表达式详解
开发语言·python
-To be number.wan4 小时前
Python数据分析:SciPy科学计算
python·学习·数据分析
Dxy12393102164 小时前
DataFrame数据修改:从基础操作到高效实践的完整指南
python·dataframe
overmind6 小时前
oeasy Python 115 列表弹栈用pop删除指定索引
开发语言·python
hnxaoli7 小时前
win10程序(十六)通达信参数清洗器
开发语言·python·小程序·股票·炒股
电饭叔7 小时前
文本为 “ok”、前景色为白色、背景色为红色,且点击后触发 processOK 回调函数的 tkinter 按钮
开发语言·python
雷电法拉珑8 小时前
财务数据批量采集
linux·前端·python
shangjian0079 小时前
Python基础-With关键字
python
zchxzl10 小时前
亲测2026京津冀可靠广告展会
大数据·人工智能·python