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})
相关推荐
chushiyunen2 小时前
python中的@Property和@Setter
java·开发语言·python
禾小西2 小时前
Java中使用正则表达式核心解析
java·python·正则表达式
yoyo_zzm2 小时前
JAVA (Springboot) i18n国际化语言配置
java·spring boot·python
weixin_408099674 小时前
图片去水印 API 接口实战:网站如何实现自动去水印(Python / PHP / C#)
图像处理·人工智能·python·c#·php·api·图片去水印
yyk的萌4 小时前
AI 应用开发工程师基础学习计划
开发语言·python·学习·ai·lua
qq_196976176 小时前
python的sql解析库-sqlparse
数据库·python·sql
:mnong6 小时前
Superpowers 项目设计分析
java·c语言·c++·python·c#·php·skills
a里啊里啊6 小时前
测试开发面试题
开发语言·chrome·python·xpath
豆沙糕6 小时前
Python异步编程从入门到实战:结合RAG流式回答全解析
开发语言·python·面试