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})
相关推荐
0566466 小时前
agent学习Day15——SQLAlchemy 查询过滤、分页与历史列表接口
python·学习·fastapi
程序员爱德华7 小时前
Python与C++:异同点对比
c++·python
hangyuekejiGEO7 小时前
GEO技术服务选型指南
大数据·人工智能·python
软萌萌的18 小时前
Java Spring Boot 修改yml配置&加载顺序规则
java·spring boot·python
Dxy12393102169 小时前
Linux 编译安装 Python 3.12.10(多版本共存,不破坏系统Python)
linux·运维·python
持敬chijing10 小时前
Python概述
开发语言·python
赤羽尾风12 小时前
NumPy快速入门
python·numpy
倒流时光三十年12 小时前
第三阶段 26 · highlight 高亮(返回命中片段)
后端·python·django
久久学姐14 小时前
Python+Playwright+Pytest+BDD,用FSM打造高效测试框架
python·pytest·bdd·playwright·fsm