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})
相关推荐
泡干脆面就番茄7 小时前
深度学习:PyTorch框架初识——MNIST手写数字识别
python·深度学习
shirsl7 小时前
算法 Day 5 树 / 二叉树 + DFS
数据结构·python·算法
门思科技7 小时前
开源网关有哪些:主流类型梳理
网络·python·物联网
szephyr7 小时前
Python 爬虫合规与反爬实战:从 requests 到 Playwright
爬虫·python·requests·playwright·反爬
E-iceblue7 小时前
Excel 列转行/行列转换全指南:从 4 种常见解法到 Python 批量自动化
python·excel·python库·spire.xls
言乐67 小时前
Python + NumPy 从零实现的 BP 神经网络(反向传播)脚本模型,包含前向传播、反向传播、训练和预测,并用 XOR 数据做示例
python·django·virtualenv·pygame·tornado
Ticnix8 小时前
多租户 RAG:让每个用户只检索到自己的知识库
后端·python·agent
ID34610744208 小时前
【课程设计】基于Spring Boot+Vue的游戏账号租赁系统的设计与实现-计算机毕设 附源码50345
javascript·vue.js·spring boot·python·node.js·php·课程设计
夏雪coding8 小时前
RAG 要不要上向量库:720 个 chunk 用 numpy 点积就够了
python·aigc·ai编程
Ticnix8 小时前
我删了 200 行 if-else,把决策逻辑全写进了 System Prompt
python·llm·agent