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})
相关推荐
飞Link4 小时前
什么是 AirSim?一文读懂无人机仿真平台
python·算法·无人机
曲径海盗5 小时前
【Python 学习第 38 天】for 循环
python·学习笔记·编程入门
在世修行5 小时前
智学文枢:变式题生成引擎
python·ai·pyside·题目生成
On The Road :7 小时前
Java 多线程详解:从入门到线程安全
java·python·安全
岁月宁静7 小时前
如何设计支持 Skills 的 Agent?一套可扩展的四层架构
python·agent
岁月宁静8 小时前
CrewAI 快速上手:10 分钟搭建你的第一个 Agent 团队
python·agent
曲径海盗8 小时前
【Python 学习第 40 天】for 循环
python·学习笔记·编程入门
专注仿真8 小时前
知识问答大模型-rag算法详解
人工智能·python·控制算法
染指11109 小时前
158.Agent-LangGraph-子图(共享状态和不共享状态模式)
开发语言·人工智能·python·ui·agent·agents
云和数据.ChenGuang10 小时前
Python 常见特殊方法详解:__new__、__init__、__del__、__str__、__repr__ 与 __getattribute__
开发语言·人工智能·python·1024程序员节