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})
相关推荐
wuyk5552 小时前
Spider-第14讲-表单提交与CSRF
前端·爬虫·python·elasticsearch·csrf
汤姆宝库2 小时前
RoPE旋转位置编码的实现与长上下文外推
python·深度学习·机器学习
用户019027581613 小时前
股票代码格式对照:各数据源代码转 AlphaFeed
python
__underline__3 小时前
冷门Python知识点005篇:list.sort( )的排序稳定性,是用0字节额外内存实现的
python·算法
贝壳6903 小时前
升到 9.13.12 我照着文档抄了两行,两次都炸了
python
VIP_CQCRE4 小时前
AI 音乐 API 上线后成本失控?用预算阈值、幂等任务和音频验收管住 Suno v6
python·api·suno·ai音乐·成本治理
2601_967980114 小时前
python list如何赋值
python·list·列表推导式·赋值·切片赋值
典学长编程5 小时前
LangGraph 快速入门:从 StateGraph 到 ReAct Agent
python·有向图·无向图·langgraph·react agent·stategraph
用户019027581617 小时前
AlphaFeed 查不到代码返回空?非法/缺后缀 symbol 的行为与处理
python
isfox7 小时前
Python 单元测试:别再用 print 调试了,写个测试一劳永逸
python