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})
相关推荐
是小蟹呀^7 小时前
【总结】LangChain中工具的使用
python·langchain·agent·tool
宝贝儿好7 小时前
【LLM】第二章:文本表示:词袋模型、小案例:基于文本的推荐系统(酒店推荐)
人工智能·python·深度学习·神经网络·自然语言处理·机器人·语音识别
王夏奇7 小时前
pythonUI界面弹窗设置的几种办法
python·ui
ZhengEnCi7 小时前
P2B-Python可迭代对象完全指南-从列表到生成器的Python编程利器
python
萌萌站起8 小时前
Vscode 中 python模块的导入问题
ide·vscode·python
是小蟹呀^8 小时前
【总结】提示词工程
python·llm·prompt·agent
YBAdvanceFu8 小时前
从零构建智能体:深入理解 ReAct Plan Solve Reflection 三大经典范式
人工智能·python·机器学习·数据挖掘·多智能体·智能体
王夏奇9 小时前
python中的__all__ 具体用法
java·前端·python
王夏奇9 小时前
pycharm中3种不同类型的python文件
ide·python·pycharm
小陈的进阶之路9 小时前
Selenium 滑动 vs Appium 滑动
python·selenium·测试工具·appium