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})
相关推荐
happylifetree22 分钟前
Python18(补充):练习
python
weixin_416667961 小时前
银河麒麟V10看门狗试验-1
网络·chrome·python
古城小栈1 小时前
Pydantic 从入门到实践全讲解
python
happylifetree1 小时前
Python18:核心语法-数据存储与运算-运算符-算术运算符
python
打工仔折腾 AI1 小时前
从Attention到BERT:双向预训练语言模型到底解决了什么问题
人工智能·后端·python·深度学习·语言模型·bert
迅猛龙办公室2 小时前
实现第一个python程序(HelloWorld)
开发语言·python
拉格朗日(Lagrange)2 小时前
【第2 章】WorkBuddy 从入门到高手
开发语言·python
老歌老听老掉牙3 小时前
斜抛运动问题分析:给定最大高度与墙面位置的轨迹与时间求解
python·斜抛运动
言乐63 小时前
Python自动去除水印
开发语言·python·django·virtualenv·pygame
czq_26867194873 小时前
Python打卡第31天
开发语言·python