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})
相关推荐
用户019027581614 小时前
Telegram Bot 股票到价提醒:AlphaFeed 轮询 + sendMessage
python
黑客笔记5 小时前
Python 进程池和线程池:用等待任务理解并发
开发语言·python
卷无止境6 小时前
Python 开发中的资源管理:统一生命周期,保留资源差异
后端·python
新*6 小时前
520 万数据迁移实战:Elasticsearch 索引重建与"改名"的完整踩坑记录
python·mysql·elasticsearch·数据迁移
吴名氏.7 小时前
Java转AI Agent教程(第十五周)政策时效:过期政策不该被召回,也不能被删掉
java·人工智能·python·ai·ai agent
黑客笔记16 小时前
python小工具win7翻车事故现场
python
岁月宁静18 小时前
从零拆解 AI 语音模拟面试系统
人工智能·python·agent
benchmark_cc18 小时前
个人开发者接入五档盘口:用 QuantDash 读取单只股票的验收清单与易错点
python·数据分析·pandas·量化交易·股票数据·quantdash
ZhengEnCi20 小时前
项目越写越乱?先别改架构:用一次目录重排 + 一份可复算的体检脚本把乱治住
python·架构·ai编程
Dmz丶20 小时前
前端转 AI 100 天 Day 45:阶段复盘——从“会调 API”到“做出 AI 产品”
python