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})
相关推荐
weixin_BYSJ19873 分钟前
【java项目分享】springboot阅读推荐平台10600
java·javascript·spring boot·python·django·flask·php
阿kun要赚马内8 分钟前
工具在langchain agent中的调用
人工智能·后端·python
Esaka_Forever17 分钟前
uvicorn main.py 命令说明
fastapi
GrowthDiary00718 分钟前
Python 常用函数总结
开发语言·python
2601_9578838444 分钟前
2026年8月:外星人笔记本维修服务揭秘
python·电脑
eric-sjq1 小时前
仅0.6B参数如何锁住超长记忆?Xiaothink-T17-RWKV5-MLA 架构深度解析:RWKV-v5 × MLA 的“降维打击“
python·架构
张小凡vip1 小时前
Python爬虫实战:高效稳定的文件下载模块设计与实现
开发语言·爬虫·python
小趴蔡ha9 小时前
02 Anaconda、Python 与机器学习开发环境入门
python·机器学习·anaconda
2401_868534789 小时前
RTOS之RT-Thread & Linux:线程/进程管理与调度核心差异分析
c++·python
数字化转型分享点滴10 小时前
富士康、蓝思科技为何选择四化信息?MES制造执行系统的实践
python·科技