【问题标题】:Display Dataframe as FastAPI output将 Dataframe 显示为 FastAPI 输出
【发布时间】:2021-07-04 12:09:00
【问题描述】:

尊敬的社区成员,

我是 FastAPI 的新手,我正在尝试将 pandas 数据框显示为 FastAPI 输出,但我无法获得所需的结果。这是我已经完成的事情:

from fastapi import FastAPI, Body, Request, Form
from pydantic import BaseModel
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates
import pandas as pd

app = FastAPI()
templates = Jinja2Templates(directory="htmlDirectory")

class NameValues(BaseModel):
    Check : str = None

@app.get("/home", response_class = HTMLResponse)
def home(request:Request):
    return templates.TemplateResponse("introduction.html", {"request": request})

@app.post("/displayDF")
async def handle_df(Check: str = Form(...)):
    print("User input : ", Check)

    test_list = [["Joe", 34, "Accounts", 10000], ["Jack", 34, "Chemistry", 20000]]
    data = pd.DataFrame(data=test_list, columns=["Name", "Age", "Dept.", "Salary"])

    return data.to_html()

输出显示如下截图:

有没有办法以熊猫数据框格式实际获得 输出? 如下所示:

另外,下面是“htmlDirectory”代码,如果必须在此处进行一些更改。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Home</title>
</head>
<body>
<h2>Please enter a string in the space provided</h2>

<form action="/displayDF" method="post">
    <input type="text" name="Check">
    <input type="submit">
</form>

</body>
</html>

【问题讨论】:

    标签: python-3.x fastapi


    【解决方案1】:

    显示您的 DataFrame 的一种方法是使用 Jinja 生成一个新的 HTML 页面,该页面将使用您的 DataFrame HTML 表示(感谢 df.to_html() 方法)。

    你可以像这个例子一样更新你的函数:

    @app.post("/displayDF")
    async def handle_df(request: Request, Check: str = Form(...)):
        print("User input : ", Check)
        test_list = [
            ["Joe", 34, "Accounts", 10000], ["Jack", 34, "Chemistry", 20000]
        ]
        data = pd.DataFrame(
            data=test_list,
            columns=["Name", "Age", "Dept.", "Salary"]
        )
        return templates.TemplateResponse(
            'df_representation.html',
            {'request': request, 'data': data.to_html()}
        )
    

    df_representation.html(您必须在 htmlDirectory 文件夹下创建这个新文件):

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>displayDF</title>
    </head>
    <body>
    <h2>DataFrame representation:</h2>
    <!-- You've to mark your data as safe,
        otherwise it'll be rendered as a string -->
        {{ data|safe }}
    </body>
    </html>
    

    结果:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>displayDF</title>
    </head>
    <body>
    <h2>DataFrame representation:</h2>
        <table border="1" class="dataframe">
      <thead>
        <tr style="text-align: right;">
          <th></th>
          <th>Name</th>
          <th>Age</th>
          <th>Dept.</th>
          <th>Salary</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <th>0</th>
          <td>Joe</td>
          <td>34</td>
          <td>Accounts</td>
          <td>10000</td>
        </tr>
        <tr>
          <th>1</th>
          <td>Jack</td>
          <td>34</td>
          <td>Chemistry</td>
          <td>20000</td>
        </tr>
      </tbody>
    </table>
    </body>
    </html>

    【讨论】:

    • 有没有办法将这个输出数据帧下载为excel,就像我们在熊猫中做“data.to_excel”一样?我可以在浏览器中添加一个下载按钮,但对如何将数据框下载为 excel 感到困惑。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-03
    • 2014-05-07
    • 2018-09-30
    • 1970-01-01
    • 2016-12-15
    • 2023-01-14
    相关资源
    最近更新 更多