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})
相关推荐
Dxy123931021612 分钟前
Python 将 JSON 字符串转换为字典
前端·python·json
堕27415 分钟前
java数据结构当中的《Lambda表达式》
java·数据结构·python
小鸡吃米…42 分钟前
TensorFlow - TensorBoard 可视化
python·tensorflow·neo4j
OPEN-Source1 小时前
给 Agent 安装技能:工具抽象、自动选工具与安全边界
人工智能·python·agent·rag·deepseek
ljxp12345681 小时前
高效删除链表重复节点
python
52Hz1181 小时前
力扣207.课程表、208.实现Trie(前缀树)
python·leetcode
骇城迷影2 小时前
从零复现GPT-2 124M
人工智能·pytorch·python·gpt·深度学习
kronos.荒2 小时前
滑动窗口:寻找字符串中的字母异位词
开发语言·python
Full Stack Developme2 小时前
spring #{} 与 ${} 区别
windows·python·spring
马腾化云东2 小时前
Agent开发应知应会(Langfuse):Langfuse Session概念详解和实战应用
人工智能·python·llm