我发现了很多与此类似的东西,但我就是不能让它发挥作用。基本上,我有一个按钮,按下它后,我想将该值返回到我的 flask 后端。
HTML 按钮:
<form action="" method="POST" ><button class="btn btn-danger" type="submit" name="delete" value="{{ item2 }}"><span class="glyphicon glyphicon-trash"></span> Delete</button> </form>
python :
@app.route('/', methods=["GET","POST"])
def home():
if request.method == 'POST':
if request.form['delete'] == post_id:
(my sql login/cursor stuff....)
sql = "DELETE FROM test_table WHERE post_id = ?"
c.execute(sql, (post_id,))
return redirect("/")
如您所见,我正在使用 jinja 填充链接(和后续变量)。它按应有的方式填充了按钮,但无法将其发送回我的 python 脚本。
更新: 当我运行它时,出现内部服务器错误。我看不到路由错误是什么,因为我无法进行调试(使用 wsgi/werkzeug)。
我想我们可以最终说,不定义 post id
是它不起作用的原因。所以我的问题是,当按钮将数据发送回 python 时,python 获取什么值(以及如何获取)?是 name=
还是 value=
还是别的?
最佳答案
你的问题是
request.form['delete'] == post_id
您从按钮 (request.form['delete']
) 获取值并尝试与不存在的变量 post_id
中的值进行比较。
如果你想从按钮中获取值并分配给变量post_id
那么你需要
post_id = request.form['delete']
或
post_id = request.form.get('delete')
然后你就可以在SQL查询中使用post_id
了。
@app.route('/', methods=["GET","POST"])
def home():
if request.method == 'POST':
post_id = request.form.get('delete')
if post_id is not None:
(my sql login/cursor stuff....)
sql = "DELETE FROM test_table WHERE post_id = ?"
c.execute(sql, (post_id,))
return redirect("/")
关于python - Flask 按钮将变量传递回 python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41026510/