烧瓶按钮将变量传递回python [英] Flask button passing variable back to python

查看:43
本文介绍了烧瓶按钮将变量传递回python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现很多与此类似的东西,但是我只是不能完全使它起作用.基本上,我有一个按钮,按下该按钮后,我想将该值返回到我的烧瓶后端.

I've found a lot of into similar to this, but I just can't quite make it work. Basically, I've got a button, and upon pressing it, I want to fire that value back to my flask backend.

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脚本不起作用.

As you can see, I'm populating the links (and subsequent variable) with jinja. It populated the button as it should, but sending it back to my python script isn't working.

更新:运行此命令时,出现内部服务器错误.我看不到路由错误是因为无法调试(使用wsgi/werkzeug).

UPDATE: When I run this, I get an internal server error. I cannot see what the routing error is because I can't get debug to work (using wsgi/werkzeug).

我认为我们可以得出结论,那就是不定义 post id 就是不起作用的原因.所以我的问题是,当按钮将数据发送回python时,python会获取什么值(以及如何获取)?是 name = 还是 value = 或其他名称?

I think we can conclusively say is that by not defining post id is why it's not working. So my question is, when the button sends data BACK to python, what value (and how) does python grab? is it name= or value= or something else?

推荐答案

您的问题是

request.form['delete'] == post_id 

您从按钮( request.form ['delete'] )获取值,然后尝试与不存在的变量 post_id 中的值进行比较.

You get value from button (request.form['delete']) and try to compare with value in variable post_id which doesn't exists.

如果要从按钮获取值并将其分配给变量 post_id ,则需要

If you want to get value from button and assign to variable post_id then you need

post_id = request.form['delete']

post_id = request.form.get('delete')

,然后可以在SQL查询中使用 post_id .

and then you can use post_id in SQL query.

@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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆