python - Embed a plot into HTML using FastAPI and Jinja2
问题描述
I am trying to display a plot that is embedded into an HTML response and I'm having no luck. I am using Jinja2 for templates. I have a plot.png
saved in my local root directory and I am trying to embed it into the HTML response.
I am getting the following messages in my terminal:
INFO: 127.0.0.1:49509 - "POST /analytics HTTP/1.1" 200 OK
INFO: 127.0.0.1:49509 - "GET /plot.png HTTP/1.1" 404 Not Found
So my guess is that my plot.png
that is saved locally cannot be accessed by my app. I am pretty new to this, so any pointers would be much appreciated!
main.py
:
from fastapi import FastAPI, Request, Form
from fastapi.templating import Jinja2Templates
app = FastAPI()
templates = Jinja2Templates(directory="templates/")
@app.get("/analytics")
async def get_plot(request: Request):
result = "Please select a user: "
return templates.TemplateResponse('plot_template.html', context={'request': request, 'result': result})
@app.post("/analytics")
async def get_plot(request: Request, username: str = Form(...)):
user_email = username + "@mycompany.com"
result = user_email
return templates.TemplateResponse('plot_template.html', context={'request': request, 'result': result})
plot_template.html
:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Sample Form</title>
</head>
<body>
<form method="post">
<label for="username">Choose a user:</label>
<select id="username" name="username">
<option value="demo">Demo User</option>
<option value="not_verified_user">Not Verified User</option>
</select>
<input type="submit" value="Submit">
</form>
<p>Result: {{ result }}</p>
<img src="plot.png" alt="Plot will display after a user is selected">
</body>
</html>
解决方案
推荐阅读
- bash - 如何在输出到不同文件之前跟踪日志文件并在每一行添加命令:单词?
- next.js - 如何在 next-auth 中保护多个 Next.js API 路由
- pdf - Ghostscript:转换 pdf 使得每一页都是一个没有单个对象/文本的图像
- html - 如何将 FastAPI 连接到前端 HTML
- azure - 将 Null 和空值从 json sink 删除到 blob 存储
- java - Java编译方法
- matlab - 在 MATLAB 中将 3D 矩阵调整为 2D 矩阵
- cassandra - 失败后重新启动 Cassandra Decommission
- sql - 查询结果的总和形成两个没有共同点的不同表
- .net-5 - SignalR MessagePack 多态性