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})
相关推荐
泡泡鱼(敲代码中)8 分钟前
Python语法技术学习笔记
开发语言·笔记·python·学习·pycharm
CTA终结者13 分钟前
量化实现难,先看交易想法有没有说清
人工智能·python
hqyjzsb33 分钟前
Python 技术人转型 AI:CAIE Level I、Level II 对比怎么选
开发语言·人工智能·python·金融·数据挖掘·数据分析·aigc
zhangzeyuaaa1 小时前
Python asyncio 事件循环演进:从手动管理到现代化实践
java·服务器·python
Yanjun2i1 小时前
Agent学习记录三:完成 Agent Loop
python·学习·agent
郝学胜_神的一滴1 小时前
Effective Python 条款 8: 同时遍历多组序列:zip 与 zip_longest 的实战避坑指南
python·pycharm
承渊政道1 小时前
【Python编程—从入门到实践】(Python字典:从基础语义到现代工程实践)
开发语言·python·pycharm·字典·嵌套
麻雀飞吧1 小时前
搜索“近期量化入门”时,先补交易理解再看 Python 和 API
人工智能·python
梦因you而美2 小时前
LangChain-ReAct-Agent 智能客服系统 · 项目技术文档
langchain·agent·fastapi·扫地机器人·langgraph·rag 检索增强·react 智能客服
名字还没想好☜2 小时前
Python 字符编码实战:encode/decode、UnicodeDecodeError 与 open 的 encoding 坑
开发语言·后端·python·编程语言