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})
相关推荐
谅望者12 分钟前
数据分析笔记14:Python文件操作
大数据·数据库·笔记·python·数据挖掘·数据分析
l1t17 分钟前
调用python函数的不同方法效率对比测试
开发语言·数据库·python·sql·duckdb
2501_9411114029 分钟前
使用Scrapy框架构建分布式爬虫
jvm·数据库·python
今天吃饺子44 分钟前
如何用MATLAB调用python实现深度学习?
开发语言·人工智能·python·深度学习·matlab
萧鼎1 小时前
Python Mahotas 图像处理库:高性能计算机视觉工具
图像处理·python·计算机视觉
破烂pan1 小时前
lmdeploy.pytorch 新模型支持代码修改
python·深度学习·llm·lmdeploy
麦麦大数据2 小时前
F047 vue3+flask微博舆情推荐可视化问答系统
python·flask·知识图谱·neo4j·推荐算法·舆情分析·舆情监测
MediaTea2 小时前
Python 第三方库:Flask(轻量级 Web 框架)
开发语言·前端·后端·python·flask
java干货2 小时前
Spring Boot 为什么“抛弃”了 spring.factories?
spring boot·python·spring