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})
相关推荐
❀搜不到33 分钟前
isat-sam分割导出掩码图
开发语言·python
Zane199442 分钟前
ClassName() 只是一步?拆开看 __new__ 和 __init__ 各自在干什么
后端·python
曾阿伦1 小时前
Trae CN Python环境调试debug指南
开发语言·python
渣男教父1 小时前
Python游戏自动化实战案例
python·编程语言
天天爱吃肉82181 小时前
【工程师笔记|新能源整车电控一次过CISPR25/BCI,汽车EMC/EMI落地十大核心设计技巧】
大数据·人工智能·笔记·python·汽车
m0_617493941 小时前
Python 使用 cryptography 实现数据加密与解密
开发语言·python
万山寒2 小时前
python依赖包导出离线安装到没有外网的服务器
服务器·开发语言·python
程序员雷欧2 小时前
LongAdder
开发语言·python
月光船幽幽2 小时前
分层阈值规避归藏协议过度重置
人工智能·python
菜冻鱼2 小时前
Python-sklearn-SVM
开发语言·人工智能·python·机器学习·支持向量机·numpy·sklearn