如何在FastAPI中接收HTML表单提交的数据?
解决FastAPI接收HTML表单提交数据的问题
第一步:修复HTML表单的结构问题
你的HTML代码存在两个核心问题,导致无法提交数据:
- 缺少包裹表单元素的
<form>标签,点击提交按钮不会触发任何数据提交行为 - 存在多余的无效
</select>闭合标签,需删除
修改后的home.html代码:
<!doctype html> <body> <!-- 添加form标签,指定提交方式为POST,提交目标接口为/submit --> <form method="post" action="/submit"> <div> <label for="age">Age</label> </div> <div> <input type="text" class="form-control" id="age" name="age" placeholder="Enter your Age"> </div> <button type="submit" class="btn btn-dark">Submit</button> </form> </body> </html>
第二步:在FastAPI中添加表单接收接口
当前main.py仅实现了返回HTML页面的GET接口,没有处理表单提交的POST逻辑。需要导入Form类,新增对应接口来接收表单数据。
修改后的main.py代码:
from fastapi import FastAPI, Form from starlette.responses import FileResponse app = FastAPI() @app.get("/") async def start(): return FileResponse("./templates/home.html") # 新增POST接口,接收表单提交的年龄数据 @app.post("/submit") async def receive_form(age: str = Form(...)): # 此处可根据需求对数据进行验证、存储等操作 return {"message": "表单提交成功", "提交的年龄": age}
额外提示
- 若需要年龄为数值类型,可将
age的类型改为int,FastAPI会自动完成类型校验 - 启动服务后,可访问
http://localhost:8000/docs,通过FastAPI自动生成的文档页面直接测试表单提交功能 - 如果需要提交后跳转至指定HTML页面,可将接口返回改为
FileResponse返回对应的页面文件
内容的提问来源于stack exchange,提问作者pyComali
相关产品推荐
相关产品推荐

