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})
相关推荐
yaoxin5211231 小时前
503. Java 反射 - 编写 ServiceFactory 类
java·开发语言·python
kyrie_sakura1 小时前
python学习笔记3 -- 流程控制语句结构
笔记·python·学习
程序员小八7772 小时前
Java 快速转 Go
java·python·golang
梦想的旅途23 小时前
Python实现企业微信文本消息发送
开发语言·python·企业微信
%473 小时前
DAY41
pytorch·python
敲代码还房贷3 小时前
VMware17 + Ubuntu22.04 共享 完整步骤
linux·python·ubuntu
测试19984 小时前
Selenium 无法定位元素的几种解决方案
自动化测试·软件测试·python·selenium·测试工具·职场和发展·测试用例
半亩码田4 小时前
C#转Python第3.6篇:Python 的 @property 比 C# 的 get/set 更灵活
java·python·c#
欧叶冲冲冲4 小时前
Python常见数据结构的CRUD(LeetCode高频版速查)
数据结构·python·leetcode
钱栈up4 小时前
Mac 开发机一键发版不用切环境:我这样改造了团队的后端部署脚本Maven编译卡住20分钟?我靠两步定位到2处隐蔽编译错误
开发语言·python·macos