我正在使用 FastAPI 创建一个 API,它接收form-data
从 HTML 页面处理数据(需要一些时间)并返回一条消息,说明此任务已完成。
这是我的后端:
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后端的返回语句只是将用户重定向到一个仅显示返回消息的新页面。我正在寻找一种替代方案,使 HTML 表单保持显示并在该表单下方显示从服务器返回的消息。例如:
我搜索了有关请求的 FastAPI 文档 https://fastapi.tiangolo.com/advanced/custom-response/,但我还没有找到任何可以避免修改我的原始 HTML 页面的内容。
您需要使用 Javascript 接口/库,例如获取API https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API,发出异步 HTTP 请求。另外,你应该使用模板 https://fastapi.tiangolo.com/advanced/templates/渲染并返回TemplateResponse
, 代替FileResponse https://fastapi.tiangolo.com/advanced/custom-response/#fileresponse,如您的代码所示。还可以找到相关答案here https://stackoverflow.com/a/73359311/17865804 and here https://stackoverflow.com/a/73358937/17865804,这显示了如何处理<form>
提交关于submit
事件,并防止导致页面重新加载的默认操作。如果您想发帖JSON
相反,看看数据这个答案 https://stackoverflow.com/a/71741617/17865804,同时发布两者Files
and Form
/JSON
数据,看一下这个答案 https://stackoverflow.com/a/70640522/17865804.
工作示例:
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})
模板/索引.html
<!DOCTYPE html>
<html>
<body>
<h1>Super resolution image treatment</h1>
<form method="post" id="myForm">
<label for="taskname" style="font-size: 20px">Task name*:</label><br>
<input type="text" name="taskname" id="taskname"><br>
<label for="tasknumber" style="font-size: 20px">Task number*:</label><br>
<input type="number" name="tasknumber" id="tasknumber">
<p style="display:inline"><b>* Cannot be null</b></p><br><br>
<input type="button" value="Start" onclick="submitForm()">
</form>
<div id="responseArea"></div>
<script>
function submitForm() {
var formElement = document.getElementById('myForm');
var data = new FormData(formElement);
fetch('/submit', {
method: 'POST',
body: data,
})
.then(resp => resp.text()) // or, resp.json(), etc.
.then(data => {
document.getElementById("responseArea").innerHTML = data;
})
.catch(error => {
console.error(error);
});
}
</script>
</body>
</html>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)