首页 > 解决方案 > 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>

标签: pythonjinja2fastapi

解决方案


推荐阅读