使用Python Flask向SQLite添加新咖啡馆时遇Method Not Allowed错误如何解决?
解决Flask /add接口Method Not Allowed问题及表单实现
问题根源
直接在浏览器地址栏访问http://127.0.0.1:5000/add发起的是GET请求,但你定义的/add路由仅允许POST方法,因此触发"Method Not Allowed"错误。同时你的静态HTML页面缺少提交表单,无法向接口发送POST请求。
解决步骤
1. 调整Flask路由,支持GET和POST方法
修改路由装饰器添加GET方法,让GET请求返回表单页面,POST请求处理数据提交:
from flask import render_template # 导入渲染模板的方法 @app.route("/add", methods=["GET", "POST"]) def post_new_cafe(): if request.method == "POST": # 原有POST请求处理逻辑 new_cafe = Cafe( name=request.form.get("name"), map_url=request.form.get("map_url"), img_url=request.form.get("img_url"), location=request.form.get("loc"), has_sockets=bool(request.form.get("sockets")), has_toilet=bool(request.form.get("toilet")), has_wifi=bool(request.form.get("wifi")), can_take_calls=bool(request.form.get("calls")), seats=request.form.get("seats"), coffee_price=request.form.get("coffee_price"), ) db.session.add(new_cafe) db.session.commit() return jsonify(response={"success": "Successfully added the new cafe."}) # GET请求时返回表单页面 return render_template("add_cafe.html")
2. 创建带提交表单的HTML页面
在Flask项目根目录下新建templates文件夹,创建add_cafe.html文件,包含所有数据库字段对应的表单控件,注意表单的method设为POST,action指向/add:
<html lang="en"> <head> <meta charset="UTF-8"> <title>Add New Cafe</title> </head> <body> <h1>Add a New Cafe</h1> <form method="POST" action="/add"> <label for="name">Cafe Name:</label> <input type="text" id="name" name="name" required><br><br> <label for="map_url">Map URL:</label> <input type="url" id="map_url" name="map_url" required><br><br> <label for="img_url">Image URL:</label> <input type="url" id="img_url" name="img_url" required><br><br> <label for="loc">Location:</label> <input type="text" id="loc" name="loc" required><br><br> <label for="sockets">Has Sockets:</label> <input type="checkbox" id="sockets" name="sockets" value="1"><br><br> <label for="toilet">Has Toilet:</label> <input type="checkbox" id="toilet" name="toilet" value="1"><br><br> <label for="wifi">Has Wifi:</label> <input type="checkbox" id="wifi" name="wifi" value="1"><br><br> <label for="calls">Can Take Calls:</label> <input type="checkbox" id="calls" name="calls" value="1"><br><br> <label for="seats">Seats:</label> <input type="text" id="seats" name="seats" required><br><br> <label for="coffee_price">Coffee Price:</label> <input type="text" id="coffee_price" name="coffee_price" required><br><br> <button type="submit">Add Cafe</button> </form> </body> </html>
3. 测试验证
- 启动Flask应用后,访问
http://127.0.0.1:5000/add,页面会显示表单 - 填写所有字段后点击"Add Cafe",表单以POST方式提交到
/add接口,数据将存入SQLite数据库,同时返回成功的JSON响应
额外说明
- Flask项目需保持标准目录结构:
templates文件夹要和运行Flask的脚本同级 - 复选框设置
value="1",勾选时request.form.get()会拿到字符串"1",转为bool是True;未勾选时拿到None,转为bool是False,匹配你的逻辑 - 若需要提交成功后跳转页面,可将返回的JSON改为
redirect(url_for("目标路由函数名"))
内容的提问来源于stack exchange,提问作者wicked00uux
相关产品推荐
相关产品推荐

