Python 在 Flask 应用程序中提交表单时出现错误请求错误的原因是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14105452/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is the cause of the Bad Request Error when submitting form in Flask application?
提问by zch
After reading many similar sounding problems and the relevant Flask docs, I cannot seem to figure out what is generating the following error upon submitting a form:
在阅读了许多类似的问题和相关的 Flask 文档后,我似乎无法弄清楚提交表单时是什么导致了以下错误:
400 Bad Request
The browser (or proxy) sent a request that this server could not understand.
400 错误请求
浏览器(或代理)发送了此服务器无法理解的请求。
While the form always displays properly, the bad request happens when I submit an HTML form that ties to either of these functions:
虽然表单始终显示正确,但当我提交与以下任一功能相关的 HTML 表单时,会发生错误请求:
@app.route('/app/business', methods=['GET', 'POST'])
def apply_business():
if request.method == 'POST':
new_account = Business(name=request.form['name_field'], email=request.form['email_field'], account_type="business",
q1=request.form['q1_field'], q2=request.form['q2_field'], q3=request.form['q3_field'], q4=request.form['q4_field'],
q5=request.form['q5_field'], q6=request.form['q6_field'], q7=request.form['q7_field'],
account_status="pending", time=datetime.datetime.utcnow())
db.session.add(new_account)
db.session.commit()
session['name'] = request.form['name_field']
return redirect(url_for('success'))
return render_template('application.html', accounttype="business")
@app.route('/app/student', methods=['GET', 'POST'])
def apply_student():
if request.method == 'POST':
new_account = Student(name=request.form['name_field'], email=request.form['email_field'], account_type="student",
q1=request.form['q1_field'], q2=request.form['q2_field'], q3=request.form['q3_field'], q4=request.form['q4_field'],
q5=request.form['q5_field'], q6=request.form['q6_field'], q7=request.form['q7_field'], q8=request.form['q8_field'],
q9=request.form['q9_field'], q10=request.form['q10_field'],
account_status="pending", time=datetime.datetime.utcnow())
db.session.add(new_account)
db.session.commit()
session['name'] = request.form['name_field']
return redirect(url_for('success'))
return render_template('application.html', accounttype="student")
The relevant part of HTML is
HTML的相关部分是
<html>
<head>
<title>apply</title>
</head>
<body>
{% if accounttype=="business" %}
<form action="{{ url_for('apply_business') }}" method=post class="application_form">
{% elif accounttype=="student" %}
<form action="{{ url_for('apply_student') }}" method=post class="application_form">
{% endif %}
<p>Full Name:</p>
<input name="name_field" placeholder="First and Last">
<p>Email Address:</p>
<input name="email_field" placeholder="[email protected]">
...
The problem for most people was not calling GETor POST, but I am doing just that in both functions, and I double checked to make sure I imported everything necessary, such as from flask import request. I also queried the database and confirmed that the additions from the form weren't added.
大多数人的问题不是调用GETor POST,但我在两个函数中都这样做,我仔细检查以确保我导入了所有必要的东西,例如from flask import request. 我还查询了数据库并确认未添加表单中的添加项。
In the Flask app, I was requesting form fields that were labeled slightly different in the HTML form. Keeping the names consistent is a must. More can be read at this question Form sending error, Flask
在 Flask 应用程序中,我请求在 HTML 表单中标记略有不同的表单字段。保持名称一致是必须的。可以在这个问题中阅读更多表格发送错误,烧瓶
采纳答案by zch
The solution was simple and uncovered in the comments. As addressed in this question, Form sending error, Flask, and pointed out by Sean Vieira,
解决方案很简单,并在评论中发现。正如在这个问题中所解决的,表单发送错误,烧瓶,并由肖恩维埃拉指出,
...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.
...问题是 Flask 在无法在 args 和表单字典中找到键时会引发 HTTP 错误。Flask 默认假设的是,如果您要求一个特定的密钥并且它不存在,那么请求中会遗漏一些东西,整个请求是无效的。
In other words, if only one form element that you request in Python cannot be found in HTML, then the POST request is not valid and the error appears, in my case without any irregularities in the traceback. For me, it was a lack of consistency with spelling: in the HTML, I labeled various form inputs
换句话说,如果只有一个您在 Python 中请求的表单元素在 HTML 中找不到,则 POST 请求无效并出现错误,在我的情况下,回溯中没有任何违规行为。对我来说,这是拼写缺乏一致性:在 HTML 中,我标记了各种表单输入
<input name="question1_field" placeholder="question one">
while in Python, when there was a POST called, I grab a nonexistent form with
在 Python 中,当调用 POST 时,我获取了一个不存在的表单
request.form['question1']
whereas, to be consistent with my HTML form names, it needed to be
而为了与我的 HTML 表单名称保持一致,它需要是
request.form['question1_field']
I hope this helps.
我希望这有帮助。

