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})
相关推荐
陈苏同学43 分钟前
MPC控制器从入门到进阶(小车动态避障变道仿真 - Python)
人工智能·python·机器学习·数学建模·机器人·自动驾驶
mahuifa1 小时前
python实现usb热插拔检测(linux)
linux·服务器·python
MyhEhud1 小时前
kotlin @JvmStatic注解的作用和使用场景
开发语言·python·kotlin
狐凄1 小时前
Python实例题:pygame开发打飞机游戏
python·游戏·pygame
漫谈网络2 小时前
Telnet 类图解析
python·自动化·netdevops·telnetlib·网络自动化运维
农夫山泉2号3 小时前
【python】—conda新建python3.11的环境报错
python·conda·python3.11
ZHOU_WUYI4 小时前
Flask Docker Demo 项目指南
python·docker·flask
码上淘金8 小时前
【Python】Python常用控制结构详解:条件判断、遍历与循环控制
开发语言·python
Brilliant Nemo8 小时前
四、SpringMVC实战:构建高效表述层框架
开发语言·python
2301_787552879 小时前
console-chat-gpt开源程序是用于 AI Chat API 的 Python CLI
人工智能·python·gpt·开源·自动化