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})
相关推荐
Thinker QAQ30 分钟前
并发编程(十一):Shared Memory 与 Message Passing——关系与组合使用
java·python·go·并发编程·shared memory·message passing
用户83562907805135 分钟前
如何使用 Python 对 Excel 数据进行分组和分级显示
后端·python
vx_Biye_Design1 小时前
django房屋租赁推荐系统78455-计算机课程设计、毕业设计
vue.js·spring boot·后端·python·django·课程设计·express
学Linux的语莫2 小时前
python中类的常见写法
开发语言·python·状态模式
dyxal3 小时前
A2A 协议 v1.0 完全指南:方法名、Agent Card、三种绑定与 FastAPI 实战
开发语言·qt·fastapi
垆边人似月.3 小时前
Python中如何使用get函数实现频次查询
服务器·前端·python
AI 编程助手GPT3 小时前
GPT 脚本别只发一个文件:用 uv 把依赖和锁一起交付
人工智能·python·gpt·uv·依赖管理
vHelios4 小时前
Python FastAPI 422 Unprocessable Entity报错排查实录 error:Invalid \\escape
fastapi
Patrick在香港4 小时前
第 16,216 次连接之后,它不干了
python·网络编程·socket·tcp·连接池
我命由我123454 小时前
Python 开发 - Python 虚拟环境
运维·开发语言·后端·python·http·https·java-ee