发送 fastAPI 响应而不从 HTML 表单 post 重定向

Send a fastAPI response without redirecting from HTML form post

我正在使用 fastAPI 创建一个 API,它从 HTML 页面接收表单,处理它(需要一些时间)并 return消息说此任务已完成。 我的 API 构建方式是:

from cgi import test
from fastapi import FastAPI, Form, Request
from starlette.responses import FileResponse

app = FastAPI()

@app.post("/")
async def swinir_dict_creation(request: Request,taskname: str = Form(...),tasknumber: int = Form(...)):

    args_to_test = {"taskname":taskname, "tasknumber":tasknumber} # dict creation
    print('\n',args_to_test,'\n')
    # my_function_does_some_data_treatment.main(args_to_test)
    # return 'Treating...'
    return 'Super resolution completed! task '+str(args_to_test["tasknumber"])+' of '+args_to_test["taskname"]+' done'

@app.get("/")
async def read_index():
    return FileResponse("index.html")

还有我的表格:

<html>
   <head>
      <h1><b>Super resolution image treatment</b></h1>   
      <body>
        <form action="http://127.0.0.1:8000/" method="post" enctype="multipart/form-data">

            <label for="taskname" style="font-size: 20px">Task name*:</label>
            <input type="text" name="taskname" id="taskname" />
    
            <label for="tasknumber" style="font-size: 20px">Task number*:</label>
            <input type="number" name="tasknumber" id="tasknumber" />

            <b><p style="display:inline"> * Cannot be null</p></b>
            <button type="submit" value="Submit">Start</button>
         </form>
      </body>
   </head>
</html>

所以前端看起来像:

当我的处理完成后,fastAPI 的 post 的 return 只是重定向到仅显示 return 消息的页面。我一直在寻找一种替代方法,它可以使表格保持显示并在此表格下方显示我想要的消息,例如:

我在 fastAPI documentation about requests 中搜索过,但我没有找到任何可以避免不修改我原来的 HTML 页面的东西。

您需要使用 Javascript interface/library,例如 Fetch API, to make an asynchronous HTTP request. Also, you should use Templates to render and return a TemplateResponse, instead of FileResponse,如您的代码所示。示例如下:

app.py

from fastapi import FastAPI, Form, Request
from fastapi.templating import Jinja2Templates

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

@app.post("/submit")
async def submit(request: Request, taskname: str = Form(...), tasknumber: int = Form(...)):
    return f'Super resolution completed! task {tasknumber} of {taskname} done'

@app.get("/")
async def index(request: Request):
    return templates.TemplateResponse("index.html", {"request": request})

模板/index.html

<html>
   <head>
      <script type="text/javascript">
         function submitForm() {
             var formElement = document.getElementById('myForm');
             var data = new FormData(formElement);
             fetch('/submit', {
                   method: 'POST',
                   body: data,
                 })
                 .then(response => response.text())
                 .then(data => {
                   document.getElementById("responseArea").innerHTML = data;
                 })
                 .catch(error => {
                   console.error(error);
                 });
         }
      </script>
   </head>
   <body>
      <h1>Super resolution image treatment</h1>
      <form method="post" id="myForm">
         <label for="taskname" style="font-size: 20px">Task name*:</label>
         <input type="text" name="taskname" id="taskname" />
         <label for="tasknumber" style="font-size: 20px">Task number*:</label>
         <input type="number" name="tasknumber" id="tasknumber" />
         <b><p style="display:inline"> * Cannot be null</p></b>
         <input type="button" value="Start" onclick="submitForm()">
      </form>
      <div id="responseArea"></div>
   </body>
</html>