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})
相关推荐
Csvn2 天前
🌟 LangChain 30 天保姆级教程 · Day 13|OutputParser 进阶!让 AI 输出自动转为结构化对象,并支持自动重试!
python·langchain
cch89182 天前
Python主流框架全解析
开发语言·python
PieroPc2 天前
一个功能强大的 Web 端标签设计和打印工具,支持服务器端直接打印到局域网打印机。Fastapi + html
前端·html·fastapi
sg_knight2 天前
设计模式实战:状态模式(State)
python·ui·设计模式·状态模式·state
好运的阿财2 天前
process 工具与子agent管理机制详解
网络·人工智能·python·程序人生·ai编程
张張4082 天前
(域格)环境搭建和编译
c语言·开发语言·python·ai
weixin_423533992 天前
【Windows11离线安装anaconda、python、vscode】
开发语言·vscode·python
Ricky111zzz2 天前
leetcode学python记录1
python·算法·leetcode·职场和发展
小白学大数据2 天前
Selenium+Python 爬虫:动态加载头条问答爬取
爬虫·python·selenium
Hui Baby2 天前
springboot读取配置文件
后端·python·flask