Flask按钮将变量传回python

2024-04-26 05:15:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我发现了很多类似的东西,但我就是做不到。基本上,我有一个按钮,按下它后,我想把这个值发回到我的烧瓶后端。

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=或其他什么东西?


Tags: nameformidsqlvaluebuttondeletepost
1条回答
网友
1楼 · 发布于 2024-04-26 05:15:16

你的问题是

request.form['delete'] == post_id 

从button(request.form['delete'])中获取值,并尝试与不存在的变量post_id中的值进行比较。

如果要从button获取值并分配给变量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("/")

相关问题 更多 >