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})
相关推荐
stephon_1001 小时前
Agent 接入 MCP 后上下文爆炸、工具选串?一种“按需激活“的工具加载方案(含实现)
人工智能·python·ai
TickDB1 小时前
统一行情 API 查 A 股、港股、美股和数字货币:code=0 不代表 symbol 一个没少
人工智能·python·websocket·mcp·行情数据 api
大貔貅喝啤酒8 小时前
Python Requests库教程
自动化测试·python·requests库
copyer_xyf9 小时前
LangChain 调用 LLM
后端·python·agent
copyer_xyf9 小时前
Prompt 组织管理
后端·python·agent
shimly1234569 小时前
python3 uvicorn 是啥?
python
CTA量化套保10 小时前
期货量化程序 time.sleep 卡死:天勤单线程与 deadline 替代
python·区块链
GIS数据转换器11 小时前
城市排水生命线安全运行监测平台深度解析
java·运维·人工智能·python·安全·数据挖掘·无人机
贤哥哥yyds11 小时前
GBK转UTF\-8编码自动转换工具 使用文档
python
数量技术宅11 小时前
2026量化前沿:从Reddit热帖到Python实战,如何用赫斯特指数(Hurst)狙击虚假突破?
开发语言·python