表单发送错误,Flask [英] Form sending error, Flask
问题描述
有两个< input type =submit>
的表单。但是,当我发送它,第二次提交会导致错误。
$ b layout :
< form action ={{url_for('index')}}method =post>
< input type =submitname =addvalue =Like>
< input type =submitname =removevalue =Dislike>
< / form>
main.py :
...
如果request.method =='POST':
如果request.form ['add']:
return重定向(url_for('index'))
elif request.form ['remove']:
return redirect(url_for('index'))
...
首先提交(add)效果不错,但是第二个(移除)...:
错误的请求浏览器(或代理)发送了一个请求,表示服务器无法理解。
如何解决这个错误?
UPD : 这非常简单: 正如@Blubber指出的那样,问题在于Flask当它无法在
request.form返回ImmutableMultiDict:
$ $ $ $ $ $ $ $ $ $ $ b如果request.form.values()中的'Like':
...
elif'不喜欢'request.form.values():
...
args
和窗体
字典中找到一个键时引发HTTP错误。 Flask假设默认情况下是,如果你要求一个特定的键而不存在,那么请求中就会有一些内容被排除在外,整个请求是无效的。
$
$ b
-
使用
request.form
的.get
方法:
if request.form.get('add',None)==Like:
#喜欢发生
elif request.form.get('remove',None)==Dislike :
#不喜欢发生
-
使用相同的
< input type =submitname =action value =赞>
< input type =submitname =actionvalue =Dislike>
#和你的代码
if request.form [action] ==Like:
#等
There is form with two <input type="submit">
. But when i'm sending it, second submit causes error.
layout:
<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:
It was pretty simple: request.form returns ImmutableMultiDict:
...
if 'Like' in request.form.values():
...
elif 'Dislike' in request.form.values():
...
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:
Use
request.form
's.get
method:if request.form.get('add', None) == "Like": # Like happened elif request.form.get('remove', None) == "Dislike": # Dislike happened
Use the same
name
attribute for both submit elements:<input type="submit" name="action" value="Like"> <input type="submit" name="action" value="Dislike"> # and in your code if request.form["action"] == "Like": # etc.
这篇关于表单发送错误,Flask的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!