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})
相关推荐
_Jimmy_8 小时前
Agent 溯源精度提升方案
人工智能·python·langchain
SamChan909 小时前
在Web应用中集成PDF多语言翻译功能:PDFTranslator API实战指南
前端·python·ai·pdf·yapi·机器翻译
天天进步20159 小时前
Python全栈项目--智能办公自动化系统
开发语言·python
颜酱10 小时前
09 | 重构项目结构
人工智能·python·langchain
kisloy11 小时前
【爬虫入门第8讲】Python爬虫反爬入门
开发语言·爬虫·python
Sisphusssss11 小时前
香橙派5plus GPIO
linux·python·ubuntu
颜酱12 小时前
08 | 把维度值同步到 Elasticsearch(生成阶段)
人工智能·python·langchain
久久学姐12 小时前
基础转码学 AI:Java+Python 双语言入门,3 个月可落地实战项目
java·python·ai·转码·实战项目
ZHOU_WUYI12 小时前
4. light wam 模型loss计算过程
开发语言·人工智能·python
nwsuaf_huasir13 小时前
【无标题】
python