表单发送错误,烧瓶 [英] Form sending error, Flask

查看:25
本文介绍了表单发送错误,烧瓶的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有两个的表格.但是当我发送它时,第二次提交会导致错误.

There is form with two <input type="submit">. But when i'm sending it, second submit causes error.

布局:

<form action="{{ url_for('index') }}" method="post">
    <input type="submit" name="add" value="Like">
    <input type="submit" name="remove" value="Dislike">
</form>

main.py:

...
if request.method == 'POST':
    if request.form['add']:
        return redirect(url_for('index'))
    elif request.form['remove']:
        return redirect(url_for('index'))
...

第一次提交(添加)效果很好,但第二次(删除)...:

First submit(add) works well, but second(remove)...:

错误请求浏览器(或代理)发送了一个该服务器无法理解的请求.

Bad Request The browser(or proxy) sent a request that this server could not understand.

我该如何解决这个错误?

How can i fix this error?

UPD:

这很简单:request.form 返回 ImmutableMultiDict:

It was pretty simple: request.form returns ImmutableMultiDict:

... 
if 'Like' in request.form.values():
     ...
elif 'Dislike' in request.form.values():
     ...

推荐答案

正如@Blubber 所指出的,问题是 Flask 在无法在 argsform 字典.Flask 默认假设的是,如果您请求一个特定的键而它不存在,那么请求中会遗漏某些内容,整个请求无效.

As @Blubber points out, the issue is that Flask raises an HTTP error when it fails to find a key in the args and form dictionaries. What Flask assumes by default is that if you are asking for a particular key and it's not there then something got left out of the request and the entire request is invalid.

还有另外两种处理您的情况的好方法:

There are two other good ways to deal with your situation:

  1. 使用request.form.get方法:

if request.form.get('add', None) == "Like":
    # Like happened
elif request.form.get('remove', None) == "Dislike":
    # Dislike happened

  • 对两个提交元素使用相同的 name 属性:

    <input type="submit" name="action" value="Like">
    <input type="submit" name="action" value="Dislike">
    
    # and in your code
    if request.form["action"] == "Like":
        # etc.
    

  • 这篇关于表单发送错误,烧瓶的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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