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})
相关推荐
Spider赵毅15 分钟前
Python爬虫踩坑实录:BeautifulSoup使用中的高频问题排查
爬虫·python·beautifulsoup
怪奇云呼军1 小时前
知识库也会注入指令?闪电智能VoiceAgent 如何防住 Prompt Injection
人工智能·python·算法·云计算·音视频
zmzb01032 小时前
Python课后习题训练记录Day194
python·opencv·计算机视觉
benchmark_cc3 小时前
批量获取量化数据时,如何设置合理的超时和重试机制?——QuantDash 高性能实战指南
开发语言·人工智能·python·pandas·量化·quantdash
2601_966949653 小时前
使用 Pandas 读取批量数据时如何避免内存溢出?QuantDash 量化数据工程师避坑指南
开发语言·python·pandas·tushare·akshare·quantdash
65岁退休Coder3 小时前
LangChain v1.3.4 笔记 - 08 MCP & 相关概念
后端·python·langchain
wdloumiga3 小时前
使用 Construct 3零基础做一些2D小游戏
python·游戏·游戏2d
用户8356290780514 小时前
使用 Python 查找和替换 Word 文档中的文本
后端·python
黑马水牛4 小时前
Carla仿真系列:9_Carla 单目障碍物测距,四种方法原理与实测
经验分享·python·深度学习·计算机视觉·ros·传感器·carla仿真
Python私教5 小时前
多个项目怎么安全合并?适配层、双轨验证与可回滚切换
python·软件架构·系统迁移