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})
相关推荐
2601_962885724 分钟前
如何用 Python 获取上证指数、沪深300、中证500 等指数行情?
开发语言·python
昔我往昔6 分钟前
LangChain_RAG_学习小结
后端·python
张张123y20 分钟前
后端第六课:Python 语法速通(0 基础入门,AI 应用开发的第一门语言)
开发语言·人工智能·python·ai·后端开发
小马不起床21 分钟前
Django 后端实战指南_10:用户扩展档案信息表
python·django·sqlite
Want59522 分钟前
Python跳动的爱心①
开发语言·python·数学建模
SamChan9023 分钟前
PDF 翻译后 1,250 变成 1.250,是错了吗?用 Python 核对数字格式
python·pdf·ocr·数据校验·文档翻译
Yolanda_202226 分钟前
30.利用GPU训练(一)
python
迅猛龙办公室35 分钟前
Python实现PM空气质量提醒
服务器·前端·python
小马不起床1 小时前
Django 后端实战指南_9:前后端完整联调和问题修复
python·django·状态模式
pride.li1 小时前
第12章 Python 教程-流程控制:循环结构
linux·服务器·python·算法