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})
相关推荐
咖啡续命又一天18 分钟前
python 自动化采集 ChromeDriver 安装
开发语言·python·自动化
松果集1 小时前
【1】数据类型2
python
且慢.5891 小时前
命令行的学习使用技巧
python
海琴烟Sunshine2 小时前
leetcode 66.加一 python
python·算法·leetcode
罗橙7号2 小时前
【pyTorch】关于PyTorch的高级索引机制理解
人工智能·pytorch·python
B站计算机毕业设计之家2 小时前
智能监控项目:Python 多目标检测系统 目标检测 目标跟踪(YOLOv8+ByteTrack 监控/交通 源码+文档)✅
python·yolo·目标检测·目标跟踪·智慧交通·交通·多目标检测
江上月5132 小时前
django与vue3的对接流程详解(下)
后端·python·django
nightunderblackcat2 小时前
四大名著智能可视化推演平台
前端·网络·爬虫·python·状态模式
小蕾Java3 小时前
PyCharm入门级详细使用手册(Python新手快速上手篇)
ide·python·pycharm
动能小子ohhh3 小时前
AI智能体(Agent)大模型入门【9】--如何在pycharm等其他编译软件调用ocr工具【只写后端代码不演示】
人工智能·python·深度学习·机器学习·pycharm·ocr